/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState } from 'react';
import { Property, Booking, UserAccount, Mechanic } from '../types';
import { 
  Shield, 
  MapPin, 
  Trash2, 
  Check, 
  X, 
  Activity, 
  Building, 
  Users, 
  Calendar, 
  IndianRupee, 
  Search, 
  Filter, 
  AlertTriangle,
  Lock,
  LogOut,
  Sliders,
  CheckSquare,
  Wrench,
  Plus,
  Phone
} from 'lucide-react';

interface AdminDashboardProps {
  currentAdmin: UserAccount;
  properties: Property[];
  bookings: Booking[];
  users: UserAccount[];
  mechanics: Mechanic[];
  onApproveProperty: (id: string, approve: boolean) => void;
  onDeleteProperty: (id: string) => void;
  onUpdateProperty: (updated: Property) => void;
  onApproveMechanic: (id: string, approve: boolean) => void;
  onDeleteMechanic: (id: string) => void;
  onAddMechanic: (mech: Mechanic) => void;
  onLogout: () => void;
}

export default function AdminDashboard({
  currentAdmin,
  properties,
  bookings,
  users,
  mechanics = [],
  onApproveProperty,
  onDeleteProperty,
  onUpdateProperty,
  onApproveMechanic,
  onDeleteMechanic,
  onAddMechanic,
  onLogout
}: AdminDashboardProps) {
  
  // State variables for administrative panels
  const [panel, setPanel] = useState<'approvals' | 'properties' | 'bookings' | 'users' | 'mechanics'>('approvals');
  const [searchTerm, setSearchTerm] = useState('');
  
  // Local edit states for properties
  const [editingPropId, setEditingPropId] = useState<string | null>(null);
  const [editTitle, setEditTitle] = useState('');
  const [editFare, setEditFare] = useState<number>(50);
  const [editSlots, setEditSlots] = useState<number>(10);

  // Form states for adding a mechanic
  const [mechName, setMechName] = useState('');
  const [mechSpecialty, setMechSpecialty] = useState('');
  const [mechPhone, setMechPhone] = useState('');
  const [mechFare, setMechFare] = useState<number>(250);
  const [mechExp, setMechExp] = useState<number>(5);
  const [mechHours, setMechHours] = useState('6 AM - 8 PM');
  const [mechLocation, setMechLocation] = useState('');
  const [mechPhoto, setMechPhoto] = useState('https://images.unsplash.com/photo-1620122303020-43ec4b6cf7f8?auto=format&fit=crop&q=80&w=200');
  const [showAddMechForm, setShowAddMechForm] = useState(false);

  // Computed systemic telemetry
  const totalUsers = users.length;
  const totalProps = properties.length;
  const pendingProps = properties.filter(p => !p.isApproved);
  const approvedProps = properties.filter(p => p.isApproved);
  const totalGrossRevenue = bookings.reduce((sum, b) => sum + (b.paymentStatus === 'Paid' ? b.totalFare : 0), 0);
  const pendingMechs = mechanics.filter(m => !m.isApproved);
  const approvedMechs = mechanics.filter(m => m.isApproved);

  // Filters
  const filteredProps = properties.filter(p => {
    const matchesSearch = p.title.toLowerCase().includes(searchTerm.toLowerCase()) || 
                          p.location.address.toLowerCase().includes(searchTerm.toLowerCase());
    return matchesSearch;
  });

  const handleStartPropEdit = (p: Property) => {
    setEditingPropId(p.id);
    setEditTitle(p.title);
    setEditFare(p.fare);
    setEditSlots(p.totalSlots);
  };

  const handleSavePropEdit = (p: Property) => {
    if (!editTitle.trim() || editFare <= 0 || editSlots <= 0) {
      alert('Ensure edits are valid positive properties.');
      return;
    }
    const updated: Property = {
      ...p,
      title: editTitle.trim(),
      fare: editFare,
      totalSlots: editSlots,
      availableSlots: editSlots // reset relative fields
    };
    onUpdateProperty(updated);
    setEditingPropId(null);
  };

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 font-sans">
      
      {/* Top Admin Header banner */}
      <header className="bg-slate-900 border-b border-slate-800 px-6 py-4 sticky top-0 z-40">
        <div className="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4">
          
          <div className="flex items-center gap-2.5">
            <div className="bg-sky-600/10 text-sky-400 p-2.5 border border-sky-500/20 rounded-xl">
              <Shield className="w-5 h-5" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h1 className="text-sm font-black text-white">System Root Command</h1>
                <span className="text-[10px] bg-red-500/10 text-red-400 border border-red-500/20 px-2 py-0.5 rounded font-mono font-bold tracking-wider">
                  MASTER BYPASS ACTIVE
                </span>
              </div>
              <p className="text-[9px] text-slate-400">Unique Identity: <span className="text-slate-300 font-mono">admin@chargepark.in</span> - Global maintenance & approvals</p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <span className="text-xs text-sky-400 bg-sky-950 px-3 py-1.5 rounded-xl border border-sky-800/40 font-mono font-bold">
              SYS VER: 1.0.4-PUNE
            </span>
            <button
              onClick={onLogout}
              className="p-2 bg-slate-800 hover:bg-rose-950 hover:text-rose-400 text-slate-300 rounded-xl transition-all border border-slate-700/60"
              title="Close System Administrator Access"
            >
              <LogOut className="w-4.5 h-4.5" />
            </button>
          </div>

        </div>
      </header>

      {/* Overview Analytics Metrics */}
      <div className="bg-slate-900/30 border-b border-slate-900 px-6 py-6 font-mono">
        <div className="max-w-7xl mx-auto grid grid-cols-2 lg:grid-cols-4 gap-4">
          
          <div className="bg-slate-900/60 p-4 rounded-xl border border-slate-800 flex items-center justify-between">
            <div>
              <span className="text-[10px] text-slate-500 font-bold uppercase block">Systemic Hubs</span>
              <strong className="text-white text-xl font-bold">{totalProps} Locations</strong>
              <div className="text-[9px] text-slate-400 mt-1">
                <span className="text-emerald-400 font-bold">{approvedProps.length} Approved</span> • <span className="text-amber-500 font-bold">{pendingProps.length} Pending</span>
              </div>
            </div>
            <Building className="w-8 h-8 text-slate-700" />
          </div>

          <div className="bg-slate-900/60 p-4 rounded-xl border border-slate-800 flex items-center justify-between">
            <div>
              <span className="text-[10px] text-slate-500 font-bold uppercase block">Registrations</span>
              <strong className="text-white text-xl font-bold">{totalUsers} Profiles</strong>
              <span className="text-[9px] text-emerald-400 block mt-1">All database records online</span>
            </div>
            <Users className="w-8 h-8 text-slate-700" />
          </div>

          <div className="bg-slate-900/60 p-4 rounded-xl border border-slate-800 flex items-center justify-between">
            <div>
              <span className="text-[10px] text-slate-500 font-bold uppercase block">Booked Slots</span>
              <strong className="text-white text-xl font-bold">{bookings.length} Orders</strong>
              <span className="text-[9px] text-slate-400 block mt-1">Both EV plugs & park docks</span>
            </div>
            <Calendar className="w-8 h-8 text-slate-700" />
          </div>

          <div className="bg-slate-900/60 p-4 rounded-xl border border-slate-800 flex items-center justify-between">
            <div>
              <span className="text-[10px] text-slate-500 font-bold uppercase block">Gross Volume</span>
              <strong className="text-emerald-400 text-xl font-black flex items-center"><IndianRupee className="w-4 h-4" />{totalGrossRevenue}</strong>
              <span className="text-[9px] text-slate-400 block mt-1">Fully online transactions processed</span>
            </div>
            <Activity className="w-8 h-8 text-emerald-500/20" />
          </div>

        </div>
      </div>

      {/* Sub navigation Switchboard */}
      <div className="bg-slate-950 px-6 py-3 border-b border-slate-800/60">
        <div className="max-w-7xl mx-auto flex flex-wrap gap-2 text-xs font-bold font-mono">
          <button
            onClick={() => setPanel('approvals')}
            className={`px-4 py-2 rounded-xl border transition-all ${
              panel === 'approvals'
                ? 'bg-amber-500 border-amber-600 text-slate-950 font-black'
                : 'bg-slate-900 border-slate-800 text-slate-400 hover:text-slate-200'
            }`}
          >
            ⚠️ Pending Approvals ({pendingProps.length + pendingMechs.length})
          </button>

          <button
            onClick={() => setPanel('properties')}
            className={`px-4 py-2 rounded-xl border transition-all ${
              panel === 'properties'
                ? 'bg-sky-600 border-sky-700 text-white font-black'
                : 'bg-slate-900 border-slate-800 text-slate-400 hover:text-slate-200'
            }`}
          >
            🏨 Manage All Hubs ({properties.length})
          </button>

          <button
            onClick={() => setPanel('bookings')}
            className={`px-4 py-2 rounded-xl border transition-all ${
              panel === 'bookings'
                ? 'bg-sky-600 border-sky-700 text-white font-black'
                : 'bg-slate-900 border-slate-800 text-slate-400 hover:text-slate-200'
            }`}
          >
            🧾 Global Booking Ledger ({bookings.length})
          </button>

          <button
            onClick={() => setPanel('users')}
            className={`px-4 py-2 rounded-xl border transition-all ${
              panel === 'users'
                ? 'bg-sky-600 border-sky-700 text-white font-black'
                : 'bg-slate-900 border-slate-800 text-slate-400 hover:text-slate-200'
            }`}
          >
            👥 Accounts Audit ({users.length})
          </button>

          <button
            onClick={() => setPanel('mechanics')}
            className={`px-4 py-2 rounded-xl border transition-all ${
              panel === 'mechanics'
                ? 'bg-sky-600 border-sky-700 text-white font-black'
                : 'bg-slate-900 border-slate-800 text-slate-400 hover:text-slate-200'
            }`}
          >
            🔧 Mechanics System ({mechanics.length})
          </button>
        </div>
      </div>

      {/* Main Panel Content */}
      <main className="max-w-7xl mx-auto px-6 py-8">
        
        {/* Panel 1: Pending Approvals from Property Owners */}
        {panel === 'approvals' && (
          <div className="space-y-6">
            <div className="border-b border-slate-800 pb-3">
              <h2 className="text-base font-black text-white">Pending Landlord Registrations</h2>
              <p className="text-xs text-slate-400">Verify charger credentials, physical location correctness and authorize them live.</p>
            </div>

            {pendingProps.length === 0 ? (
              <div className="bg-slate-900/60 border border-slate-850 p-12 rounded-3xl text-center max-w-sm mx-auto space-y-2">
                <CheckSquare className="w-10 h-10 text-emerald-400 mx-auto" />
                <span className="font-extrabold text-white text-sm block">Database Clean!</span>
                <p className="text-slate-400 text-xs">There are no pending owner requests listed. All partner stations are verified and active.</p>
              </div>
            ) : (
              <div className="space-y-4">
                {pendingProps.map((prop) => (
                  <div key={prop.id} className="bg-slate-900 border border-amber-500/20 rounded-2xl overflow-hidden p-5 flex flex-col md:flex-row justify-between gap-6 hover:border-amber-500/40 transition-all">
                    
                    <div className="space-y-3 flex-1">
                      
                      <div className="space-y-1">
                        <div className="flex items-center gap-2">
                          <span className="text-[10px] bg-amber-500 text-slate-950 font-black px-1.5 py-0.5 rounded uppercase tracking-wider font-mono">
                            PENDING VERIFICATION
                          </span>
                          <span className="text-xs text-slate-400 font-semibold font-mono">Owner ID: {prop.ownerId || 'Anonymous'}</span>
                        </div>
                        <h4 className="text-base font-black text-white leading-tight">{prop.title}</h4>
                      </div>

                      <p className="text-xs text-slate-400 flex items-center gap-1.5 font-medium">
                        <MapPin className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
                        <span>{prop.location.address}, {prop.location.city}</span>
                      </p>

                      <p className="text-xs text-slate-300 italic max-w-2xl leading-relaxed">{prop.description}</p>

                      <div className="flex flex-wrap gap-1 items-center">
                        <span className="text-[10px] text-slate-400 font-bold">Amenities:</span>
                        {prop.amenities.map((a, i) => (
                          <span key={i} className="text-[9px] bg-slate-950 text-slate-400 px-1.5 py-0.5 rounded-md font-mono">
                            {a}
                          </span>
                        ))}
                      </div>

                    </div>

                    <div className="flex flex-col justify-between items-end border-t md:border-t-0 border-slate-800 pt-4 md:pt-0 shrink-0 w-full md:w-44 space-y-4">
                      
                      <div className="text-right w-full font-mono">
                        <span className="text-[10px] text-slate-500 block uppercase font-bold">Rates & capacity</span>
                        <div className="text-sm font-bold text-white">₹{prop.fare}/hr Rate</div>
                        <div className="text-xs text-slate-400">{prop.totalSlots} Parking slots</div>
                        {prop.chargerTypes && prop.chargerTypes.length > 0 && (
                          <div className="text-[9px] text-emerald-400 italic">⚡ Charging Available</div>
                        )}
                      </div>

                      {/* Acceptance Swithes */}
                      <div className="flex gap-2 w-full">
                        <button
                          onClick={() => {
                            if (window.confirm('Reject and permanently purge this listing request from database?')) {
                              onDeleteProperty(prop.id);
                            }
                          }}
                          className="flex-1 py-2 bg-slate-950 hover:bg-rose-950 text-rose-400 border border-slate-850 rounded-xl font-bold text-xs transition-all flex items-center justify-center gap-1"
                        >
                          <X className="w-3.5 h-3.5" />
                          <span>Reject</span>
                        </button>

                        <button
                          onClick={() => {
                            onApproveProperty(prop.id, true);
                          }}
                          className="flex-1 py-2 bg-gradient-to-r from-emerald-600 to-teal-600 text-white rounded-xl font-black text-xs hover:from-emerald-500 hover:to-teal-500 transition-all shadow-md flex items-center justify-center gap-1"
                        >
                          <Check className="w-3.5 h-3.5" />
                          <span>Verify Live</span>
                        </button>
                      </div>

                    </div>

                  </div>
                ))}
              </div>
            )}

            <div className="border-b border-slate-800 pb-3 mt-10 pt-4">
              <h2 className="text-base font-black text-white">Pending Mechanic Registrations</h2>
              <p className="text-xs text-slate-400 font-medium">Validate mechanic credentials, on-call base fares, and unlock them for 24/7 on-demand dispatch.</p>
            </div>

            {pendingMechs.length === 0 ? (
              <div className="bg-slate-900/60 border border-slate-850 p-10 rounded-3xl text-center max-w-sm mx-auto space-y-2 select-none">
                <CheckSquare className="w-8 h-8 text-emerald-400 mx-auto" />
                <span className="font-extrabold text-white text-sm block">All Mechanics Approved!</span>
                <p className="text-slate-400 text-[11px] leading-relaxed">No pending requests are in the queue. All partners are actively authorized.</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {pendingMechs.map((mech) => (
                  <div key={mech.id} className="bg-slate-900 border border-amber-500/20 rounded-2xl p-4 flex gap-4 items-center justify-between hover:border-amber-500/40 transition">
                    <div className="flex items-center gap-3">
                      <img src={mech.photo} className="w-11 h-11 rounded-full object-cover border border-slate-800 shrink-0" alt="" referrerPolicy="no-referrer" />
                      <div className="text-left">
                        <strong className="text-white block font-bold text-sm">{mech.name}</strong>
                        <span className="text-[10px] text-amber-400 font-bold block">{mech.specialty}</span>
                        <span className="text-[10px] text-slate-450 block font-mono font-medium">📞 {mech.phone} • {mech.experienceYears} Years Exp • ₹{mech.baseFare} Base</span>
                      </div>
                    </div>
                    <div className="flex gap-1.5 shrink-0">
                      <button
                        onClick={() => {
                          if (window.confirm(`Reject and delete ${mech.name}?`)) {
                            onDeleteMechanic(mech.id);
                          }
                        }}
                        className="p-2 bg-slate-950 hover:bg-rose-950 text-rose-450 border border-slate-850 rounded-xl transition"
                        title="Reject Mechanic"
                      >
                        <X className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => onApproveMechanic(mech.id, true)}
                        className="py-1.5 px-3 bg-gradient-to-r from-emerald-600 to-teal-600 text-white hover:from-emerald-500 hover:to-teal-500 rounded-xl font-bold text-xs transition flex items-center gap-1 shadow-md"
                      >
                        <Check className="w-3.5 h-3.5 animate-pulse" />
                        <span>Approve</span>
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}

          </div>
        )}

        {/* Panel 2: General Hubs Admin panel */}
        {panel === 'properties' && (
          <div className="space-y-6">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-800 pb-4">
              <div>
                <h2 className="text-base font-black text-white">Global Properties Database</h2>
                <p className="text-xs text-slate-400">Search and adapt listed spots and make instantaneous changes over price tags and slots.</p>
              </div>

              {/* Instant Search Bar */}
              <div className="relative w-full sm:w-64">
                <Search className="absolute left-3 top-2.5 w-4 h-4 text-slate-500" />
                <input
                  type="text"
                  placeholder="Filter by title/address..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-9 pr-4 py-1.5 bg-slate-900 border border-slate-800 text-xs rounded-xl focus:border-sky-500 outline-none text-slate-200"
                />
              </div>
            </div>

            <div className="bg-slate-900 rounded-2xl overflow-x-auto border border-slate-800">
              <table className="w-full text-left text-xs border-collapse">
                <thead>
                  <tr className="bg-slate-950 border-b border-slate-800 text-slate-400 uppercase text-[9px] font-bold font-mono">
                    <th className="p-4">Spot Details</th>
                    <th className="p-4">Type</th>
                    <th className="p-4">Hourly Price</th>
                    <th className="p-4">Slots</th>
                    <th className="p-4">Status</th>
                    <th className="p-4 text-center">Operations</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800/60">
                  {filteredProps.map((p) => {
                    const isEditing = editingPropId === p.id;
                    return (
                      <tr key={p.id} className="hover:bg-slate-950/40 transition-colors">
                        
                        {/* Title and location */}
                        <td className="p-4 max-w-sm">
                          {isEditing ? (
                            <input
                              type="text"
                              value={editTitle}
                              onChange={(e) => setEditTitle(e.target.value)}
                              className="w-full px-2 py-1 bg-slate-950 border border-slate-800 rounded font-bold text-white text-xs"
                            />
                          ) : (
                            <div>
                              <strong className="text-white font-bold block">{p.title}</strong>
                              <span className="text-slate-400 text-[10px] block">{p.location.address}</span>
                            </div>
                          )}
                        </td>

                        {/* Property Type */}
                        <td className="p-4">
                          <span className="px-2 py-0.5 rounded text-[10px] font-semibold bg-slate-950 capitalize border border-slate-850">
                            {p.type}
                          </span>
                        </td>

                        {/* Price */}
                        <td className="p-4">
                          {isEditing ? (
                            <input
                              type="number"
                              value={editFare}
                              onChange={(e) => setEditFare(Number(e.target.value))}
                              className="w-16 px-2 py-1 bg-slate-950 border border-slate-800 rounded font-bold text-emerald-400 text-xs"
                            />
                          ) : (
                            <span className="font-bold text-white font-mono">₹{p.fare}/hr</span>
                          )}
                        </td>

                        {/* Total Capacity slots */}
                        <td className="p-4">
                          {isEditing ? (
                            <input
                              type="number"
                              value={editSlots}
                              onChange={(e) => setEditSlots(Number(e.target.value))}
                              className="w-16 px-2 py-1 bg-slate-950 border border-slate-800 rounded font-bold text-white text-xs"
                            />
                          ) : (
                            <span className="font-mono">{p.totalSlots} Slots</span>
                          )}
                        </td>

                        {/* Approved state */}
                        <td className="p-4">
                          <button
                            onClick={() => onApproveProperty(p.id, !p.isApproved)}
                            className={`px-2.5 py-0.5 rounded text-[9px] font-bold uppercase transition-all
                              ${p.isApproved 
                                ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' 
                                : 'bg-amber-500/10 text-amber-500 border border-amber-500/20'}`}
                          >
                            {p.isApproved ? '🟢 Verified Live' : '🟠 Tap to Approve'}
                          </button>
                        </td>

                        {/* Admin Action triggers */}
                        <td className="p-4 text-center">
                          <div className="flex items-center justify-center gap-2">
                            {isEditing ? (
                              <>
                                <button
                                  onClick={() => handleSavePropEdit(p)}
                                  className="px-2.5 py-1 bg-emerald-600 text-white font-bold rounded text-[10px] hover:bg-emerald-500"
                                >
                                  Save
                                </button>
                                <button
                                  onClick={() => setEditingPropId(null)}
                                  className="px-2 py-1 bg-slate-800 text-slate-300 font-bold rounded text-[10px]"
                                >
                                  Back
                                </button>
                              </>
                            ) : (
                              <>
                                <button
                                  onClick={() => handleStartPropEdit(p)}
                                  className="text-[10px] text-sky-400 hover:underline px-1.5 py-0.5 bg-slate-950 border border-slate-800 rounded"
                                >
                                  Edit
                                </button>
                                <button
                                  onClick={() => {
                                    if (window.confirm(`Delete property slot ID: "${p.title}"?`)) {
                                      onDeleteProperty(p.id);
                                    }
                                  }}
                                  className="text-rose-400 hover:text-rose-300 px-1.5 py-0.5 bg-rose-950/40 border border-rose-900/60 rounded"
                                >
                                  Purge
                                </button>
                              </>
                            )}
                          </div>
                        </td>

                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Panel 3: Master Booking list ledger */}
        {panel === 'bookings' && (
          <div className="space-y-6">
            <div className="border-b border-slate-800 pb-3">
              <h2 className="text-base font-black text-white">App-wide Bookings Register</h2>
              <p className="text-xs text-slate-400">Total transaction transparency. Review slots booked across Bihar in chronological order.</p>
            </div>

            {bookings.length === 0 ? (
              <div className="bg-slate-900/60 p-8 rounded-2xl text-center text-slate-500 border border-slate-850">
                No bookings registered globally in this development sandbox container.
              </div>
            ) : (
              <div className="bg-slate-900 border border-slate-800 rounded-3xl overflow-hidden text-xs">
                <table className="w-full text-left">
                  <thead>
                    <tr className="bg-slate-950 text-slate-500 text-[10px] font-bold uppercase border-b border-slate-800">
                      <th className="p-4">Booking ID</th>
                      <th className="p-4">Customer Details</th>
                      <th className="p-4">Reservoir Spot</th>
                      <th className="p-4">Slot Period</th>
                      <th className="p-4">Fare Total</th>
                      <th className="p-4">Payment Method</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-800/60 font-mono text-slate-300">
                    {bookings.map((b) => (
                      <tr key={b.id} className="hover:bg-slate-950/20">
                        <td className="p-4 text-slate-500 text-[10px] font-bold">{b.id}</td>
                        <td className="p-4 font-sans">
                          <strong className="text-white block font-bold">{b.userName}</strong>
                          <span className="text-[10px] text-slate-400 block">{b.userEmail}</span>
                          <span className="text-[9px] bg-slate-950 text-amber-500 px-1 border border-slate-850 rounded">{b.vehicleNumber} ({b.vehicleType})</span>
                        </td>
                        <td className="p-4 font-sans font-bold text-teal-400 max-w-xs truncate" title={b.propertyTitle}>
                          {b.propertyTitle}
                        </td>
                        <td className="p-4">
                          <span className="block text-white text-[11px]">{b.bookingDate}</span>
                          <span className="text-slate-500 text-[10px] block">{b.timeSlot}</span>
                        </td>
                        <td className="p-4 text-emerald-400 font-extrabold text-sm">₹{b.totalFare}</td>
                        <td className="p-4">
                          <span className="capitalize font-bold text-slate-100 bg-slate-950 px-2 py-0.5 border border-slate-800 rounded">
                            {b.paymentMethod === 'COD' ? 'Arrival COD' : b.paymentMethod}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}

        {/* Panel 4: Accounts audit list */}
        {panel === 'users' && (
          <div className="space-y-6">
            <div className="border-b border-slate-800 pb-3">
              <h2 className="text-base font-black text-white">Database Profiles Audit List</h2>
              <p className="text-xs text-slate-400">Review all driver register credentials and partner owner accounts bypass values.</p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {users.map((usr) => (
                <div key={usr.id} className="bg-slate-900 border border-slate-800 rounded-2xl p-4 flex justify-between items-center">
                  <div>
                    <div className="flex items-center gap-1.5">
                      <strong className="text-white font-bold text-sm block">{usr.name}</strong>
                      <span className={`text-[9px] font-bold px-1.5 py-0.3 rounded uppercase
                        ${usr.role === 'admin' ? 'bg-rose-500 text-slate-950' : 
                          usr.role === 'owner' ? 'bg-emerald-500 text-slate-950' : 'bg-slate-800 text-slate-300'}`}>
                        {usr.role}
                      </span>
                    </div>
                    <span className="text-xs text-slate-400 block font-mono">{usr.email}</span>
                    <span className="text-[10px] text-slate-500 font-mono block">Registered: {new Date(usr.createdAt).toLocaleDateString()}</span>
                  </div>

                  <div className="text-right">
                    {usr.isEmailVerified ? (
                      <span className="text-[10px] text-emerald-400 font-bold bg-emerald-950/30 px-2 py-1 rounded-xl border border-emerald-900/40">
                        ✓ Verified Email
                      </span>
                    ) : (
                      <span className="text-[10px] text-amber-500 font-bold bg-amber-950/30 px-2 py-1 rounded-xl border border-amber-900/40 animate-pulse">
                        ⚠ Pending Email Code
                      </span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Panel 5: Mechanics Management Panel */}
        {panel === 'mechanics' && (
          <div className="space-y-6">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-800 pb-4">
              <div>
                <h2 className="text-lg font-black text-white flex items-center gap-2">
                  <Wrench className="w-5 h-5 text-amber-400" />
                  <span>On-Demand Mechanics Registry</span>
                </h2>
                <p className="text-xs text-slate-400">Add, audit, or approve mobile repair technicians across Bihar districts.</p>
              </div>

              <button
                type="button"
                onClick={() => setShowAddMechForm(!showAddMechForm)}
                className="self-start sm:self-auto px-4 py-2 bg-amber-500 hover:bg-amber-400 text-slate-950 font-extrabold text-xs rounded-xl shadow-md transition flex items-center gap-1.5"
              >
                <Plus className="w-4 h-4" />
                <span>{showAddMechForm ? 'Cancel Add' : 'Register Mechanic'}</span>
              </button>
            </div>

            {/* Hidden Add Mechanic form panel */}
            {showAddMechForm && (
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  if (!mechName.trim() || !mechSpecialty.trim() || !mechPhone.trim() || !mechLocation.trim()) {
                    alert('Please fill out all required mechanic fields.');
                    return;
                  }
                  
                  const newMech: Mechanic = {
                    id: 'mech-' + Math.random().toString(36).substring(2, 9),
                    name: mechName.trim(),
                    specialty: mechSpecialty.trim(),
                    phone: mechPhone.trim(),
                    experienceYears: Number(mechExp) || 3,
                    rating: 5.0, // starts flat with five star rating
                    baseFare: Number(mechFare) || 250,
                    availabilityHours: mechHours,
                    isApproved: true, // admin created is approved automatically
                    location: mechLocation.trim(),
                    photo: mechPhoto.trim() || 'https://images.unsplash.com/photo-1620122303020-43ec4b6cf7f8?auto=format&fit=crop&q=80&w=200'
                  };

                  onAddMechanic(newMech);
                  
                  // Reset form
                  setMechName('');
                  setMechSpecialty('');
                  setMechPhone('');
                  setMechFare(250);
                  setMechExp(5);
                  setMechLocation('');
                  setShowAddMechForm(false);
                }}
                className="bg-slate-900 border border-slate-800 rounded-3xl p-6 space-y-4 text-left max-w-2xl"
              >
                <h3 className="text-sm font-bold text-slate-200">Register Certified Support Partner</h3>
                
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide">Full Name *</label>
                    <input
                      type="text"
                      required
                      value={mechName}
                      onChange={(e) => setMechName(e.target.value)}
                      placeholder="e.g. Ramesh Deshmukh"
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-3 py-2 text-xs text-white outline-none"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide">Specialty / Expert Field *</label>
                    <input
                      type="text"
                      required
                      value={mechSpecialty}
                      onChange={(e) => setMechSpecialty(e.target.value)}
                      placeholder="e.g. EV Inverter & AC Charging Diagnostics"
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-3 py-2 text-xs text-white outline-none"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide">Phone Number *</label>
                    <input
                      type="text"
                      required
                      value={mechPhone}
                      onChange={(e) => setMechPhone(e.target.value)}
                      placeholder="e.g. +91 98900 11223"
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-3 py-2 text-xs text-white outline-none"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide">Operating Region / Address *</label>
                    <input
                      type="text"
                      required
                      value={mechLocation}
                      onChange={(e) => setMechLocation(e.target.value)}
                      placeholder="e.g. Baner & Aundh On-Call"
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-3 py-2 text-xs text-white outline-none"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide">Base Repairing Charge (Rupees) *</label>
                    <input
                      type="number"
                      required
                      min={100}
                      value={mechFare}
                      onChange={(e) => setMechFare(Number(e.target.value))}
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-3 py-2 text-xs text-white outline-none font-mono"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide">Experience (Years) *</label>
                    <input
                      type="number"
                      required
                      min={1}
                      value={mechExp}
                      onChange={(e) => setMechExp(Number(e.target.value))}
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-3 py-2 text-xs text-white outline-none font-mono"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide">Shift / Working Hours *</label>
                    <select
                      value={mechHours}
                      onChange={(e) => setMechHours(e.target.value)}
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-3 py-2 text-xs text-white outline-none"
                    >
                      <option value="6 AM - 8 PM">Normal Dispatch hours (6 AM - 8 PM)</option>
                      <option value="24/7 On-Call Cycle">Dispatched 24/7 Emergency Support</option>
                    </select>
                  </div>

                  <div className="space-y-1">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide">Profile Image URL (Optional)</label>
                    <input
                      type="url"
                      value={mechPhoto}
                      onChange={(e) => setMechPhoto(e.target.value)}
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-3 py-2 text-xs text-white outline-none"
                    />
                  </div>
                </div>

                <div className="flex justify-end gap-2 pt-2">
                  <button
                    type="submit"
                    className="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white font-extrabold text-xs rounded-xl shadow-md transition"
                  >
                    Add and Verify Mechanic
                  </button>
                </div>
              </form>
            )}

            {/* Mechanics grid list */}
            {approvedMechs.length === 0 ? (
              <div className="bg-slate-900/60 border border-slate-850 p-12 rounded-3xl text-center max-w-sm mx-auto select-none">
                <Wrench className="w-10 h-10 text-slate-500 mx-auto animate-pulse" />
                <span className="font-extrabold text-white text-sm block mt-2">No Active Mechanics!</span>
                <p className="text-slate-400 text-xs mt-1">Please register a certified technician or approve pending applicants to populate the team.</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {approvedMechs.map((mech) => (
                  <div key={mech.id} className="bg-slate-900 border border-slate-800/80 rounded-2xl p-4 space-y-3 relative overflow-hidden group hover:border-slate-700 transition">
                    <div className="flex items-start gap-3">
                      <img
                        src={mech.photo}
                        alt={mech.name}
                        className="w-12 h-12 rounded-full object-cover border border-slate-800 shrink-0"
                        referrerPolicy="no-referrer"
                      />
                      <div className="text-left flex-1">
                        <div className="flex items-center gap-1">
                          <h4 className="text-sm font-extrabold text-white">{mech.name}</h4>
                          <span className="text-[9px] bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 px-1 py-0.2 rounded font-mono font-bold uppercase">
                            LIVE
                          </span>
                        </div>
                        <span className="text-[10px] text-slate-400 block line-clamp-1 font-bold">{mech.specialty}</span>
                        <p className="text-[10px] text-slate-500 font-medium font-mono tracking-tight mt-0.5">📞 {mech.phone}</p>
                      </div>
                    </div>

                    <div className="bg-slate-950 p-2.5 rounded-xl border border-slate-850/60 grid grid-cols-3 gap-1 text-[10px] text-slate-400 font-mono text-center">
                      <div>
                        <span className="text-[8px] text-slate-600 block leading-tight font-sans uppercase">Base Charge</span>
                        <strong className="text-white font-extrabold">₹{mech.baseFare}</strong>
                      </div>
                      <div>
                        <span className="text-[8px] text-slate-600 block leading-tight font-sans uppercase">Exp</span>
                        <strong className="text-white font-extrabold">{mech.experienceYears} Years</strong>
                      </div>
                      <div>
                        <span className="text-[8px] text-slate-600 block leading-tight font-sans uppercase">Duty Hours</span>
                        <strong className="text-amber-400 font-extrabold text-[9px]">{mech.availabilityHours}</strong>
                      </div>
                    </div>

                    <div className="flex gap-2 justify-between items-center bg-slate-950/20 pt-1 text-[10px] text-slate-400 select-none">
                      <span className="font-mono text-slate-500 truncate" title={mech.location}>📍 {mech.location || "Bihar Mobile"}</span>
                      
                      <button
                        type="button"
                        onClick={() => {
                          if (window.confirm(`Are you sure you want to revoke and delete ${mech.name}'s system credentials?`)) {
                            onDeleteMechanic(mech.id);
                          }
                        }}
                        className="text-xs text-rose-400 hover:text-rose-300 font-semibold flex items-center gap-1 hover:underline pl-2 bg-rose-500/5 hover:bg-rose-500/10 px-2 py-1 rounded-lg border border-rose-500/10 shrink-0"
                        title="Remove mechanic access"
                      >
                        <Trash2 className="w-3 h-3" />
                        <span>Revoke</span>
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

      </main>

    </div>
  );
}
