import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTransportStore } from '../../store/transport';
import { 
  Bus, Map, Users, Search, Plus, Filter, 
  ChevronRight, CheckCircle2, ShieldAlert, Navigation, 
  MapPin, Hash, X, Sparkles, User, Wrench, ClipboardCheck, History
} from 'lucide-react';
import AttendanceTakeView from '../../components/AttendanceTakeView';
import AttendanceHistoryView from '../../components/AttendanceHistoryView';
import SearchableSelect from '../../components/ui/SearchableSelect';
import api from '../../store/api';

export default function TransportDashboard() {
  const { 
    vehicles, routes, allocations, loading,
    fetchVehicles, fetchRoutes, fetchAllocations,
    addVehicle, addRoute, allocateTransport,
    deallocateTransport, assignRouteUnit
  } = useTransportStore();

  const [activeTab, setActiveTab] = useState('fleet'); // fleet, routes, allocations, attendance, history
  const [search, setSearch] = useState('');
  
  const [showVehicleModal, setShowVehicleModal] = useState(false);
  const [showRouteModal, setShowRouteModal] = useState(false);
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [showAssignUnitModal, setShowAssignUnitModal] = useState(false);

  const [drivers, setDrivers] = useState<any[]>([]);
  const [manifestFilter, setManifestFilter] = useState<'allocated' | 'unallocated' | 'all'>('allocated');

  const [students, setStudents] = useState<any[]>([]);
  const [pickupPoints, setPickupPoints] = useState<any[]>([]);
  const [vehicleRoutes, setVehicleRoutes] = useState<any[]>([]);



  // Form states
  const [vehicleForm, setVehicleForm] = useState({
    registration_number: '',
    model: '',
    capacity: '',
    vehicle_type: 'bus',
    fuel_type: 'Diesel',
    description: ''
  });

  const [routeForm, setRouteForm] = useState({
    name: '',
    code: '',
    start_point: '',
    end_point: '',
    distance_km: '',
    estimated_time_minutes: '',
    description: '',
    vehicle_id: '',
    driver_id: ''
  });

  const [assignUnitForm, setAssignUnitForm] = useState({
    route_id: '',
    vehicle_id: '',
    driver_id: ''
  });

  const [assignForm, setAssignForm] = useState({
    student_id: '',
    route_id: '',
    pickup_point_id: '',
    vehicle_route_id: '',
    fee_amount: '',
    effective_from: '',
    effective_to: ''
  });

  const closeVehicleModal = () => {
    setShowVehicleModal(false);
    setVehicleForm({
      registration_number: '',
      model: '',
      capacity: '',
      vehicle_type: 'bus',
      fuel_type: 'Diesel',
      description: ''
    });
  };

  const closeRouteModal = () => {
    setShowRouteModal(false);
    setRouteForm({
      name: '',
      code: '',
      start_point: '',
      end_point: '',
      distance_km: '',
      estimated_time_minutes: '',
      description: '',
      vehicle_id: '',
      driver_id: ''
    });
  };

  const closeAssignModal = () => {
    setShowAssignModal(false);
    setAssignForm({
      student_id: '',
      route_id: '',
      pickup_point_id: '',
      vehicle_route_id: '',
      fee_amount: '',
      effective_from: '',
      effective_to: ''
    });
  };

  const handleAddVehicle = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await addVehicle({
        ...vehicleForm,
        capacity: parseInt(vehicleForm.capacity) || 0
      });
      closeVehicleModal();
    } catch (err) {
      console.error('Error registering vehicle:', err);
    }
  };

  const handleAddRoute = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await addRoute({
        ...routeForm,
        distance_km: parseFloat(routeForm.distance_km) || 0,
        estimated_time_minutes: parseInt(routeForm.estimated_time_minutes) || 0,
        vehicle_id: routeForm.vehicle_id ? parseInt(routeForm.vehicle_id) : null,
        driver_id: routeForm.driver_id ? parseInt(routeForm.driver_id) : null
      });
      closeRouteModal();
    } catch (err) {
      console.error('Error defining route:', err);
    }
  };

  const handleAllocateTransport = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await allocateTransport({
        student_id: parseInt(assignForm.student_id),
        route_id: parseInt(assignForm.route_id),
        pickup_point_id: assignForm.pickup_point_id ? parseInt(assignForm.pickup_point_id) : null,
        vehicle_route_id: assignForm.vehicle_route_id ? parseInt(assignForm.vehicle_route_id) : null,
        fee_amount: parseFloat(assignForm.fee_amount) || 0,
        effective_from: assignForm.effective_from || null,
        effective_to: assignForm.effective_to || null
      });
      closeAssignModal();
    } catch (err) {
      console.error('Error allocating transport:', err);
    }
  };

  useEffect(() => {
    setSearch('');
    if (activeTab === 'allocations') {
      api.get('/transport/pickup-points').then(res => setPickupPoints(res.data)).catch(() => {});
      api.get('/transport/vehicle-routes').then(res => setVehicleRoutes(res.data)).catch(() => {});
    }
  }, [activeTab]);

  useEffect(() => {
    fetchVehicles();
    fetchRoutes();
    fetchAllocations();
    
    // Load students for history view
    api.get('/users', { params: { role: 'student', limit: 1000 } }).then(res => {
      const data = Array.isArray(res.data) ? res.data : (res.data?.users || []);
      setStudents(data.map((s: any) => ({
        id: s.id,
        full_name: `${s.first_name} ${s.last_name}`,
        class_name: s.class_name
      })));
    });

    // Load drivers
    api.get('/users', { params: { role: 'driver', limit: 100 } }).then(res => {
      const data = Array.isArray(res.data) ? res.data : (res.data?.users || []);
      setDrivers(data.map((d: any) => ({
        id: d.id,
        full_name: `${d.first_name} ${d.last_name}`
      })));
    }).catch(() => {});

    const interval = setInterval(() => {
        fetchVehicles();
        fetchRoutes();
        fetchAllocations();
    }, 30000); // 30s polling

    return () => clearInterval(interval);
  }, [fetchVehicles, fetchRoutes, fetchAllocations]);

  const stats = [
    { label: 'Total Fleet', value: vehicles.length, icon: Bus, color: 'blue' },
    { label: 'Active Routes', value: routes.length, icon: Map, color: 'emerald' },
    { label: 'Assigned Students', value: allocations.filter(a => a.status === 'active').length, icon: Users, color: 'purple' },
    { label: 'Maintenance', value: vehicles.filter(v => v.status === 'maintenance').length, icon: Wrench, color: 'orange' },
  ];

  // FIXED: Always show all stats regardless of active tab
  const visibleStats = stats;

  const getStatColors = (color: string) => {
    switch (color) {
      case 'blue': return 'bg-blue-50 text-blue-600 border-blue-100 dark:bg-blue-900/20 dark:text-blue-400 dark:border-blue-800';
      case 'emerald': return 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-800';
      case 'orange': return 'bg-orange-50 text-orange-600 border-orange-100 dark:bg-orange-900/20 dark:text-orange-400 dark:border-orange-800';
      case 'purple': return 'bg-purple-50 text-purple-600 border-purple-100 dark:bg-purple-900/20 dark:text-purple-400 dark:border-purple-800';
      default: return 'bg-muted text-text-muted border-border';
    }
  };

  const filteredStudents = students.filter(s => {
    const matchesSearch = s.full_name.toLowerCase().includes(search.toLowerCase()) ||
      (s.class_name && s.class_name.toLowerCase().includes(search.toLowerCase()));
    
    const activeAlloc = allocations.find(a => a.student_id === s.id && a.status === 'active');
    
    let matchesAlloc = false;
    if (activeAlloc) {
      matchesAlloc = (activeAlloc.route_title && activeAlloc.route_title.toLowerCase().includes(search.toLowerCase())) ||
        (activeAlloc.vehicle_number && activeAlloc.vehicle_number.toLowerCase().includes(search.toLowerCase())) ||
        (activeAlloc.stop_name && activeAlloc.stop_name.toLowerCase().includes(search.toLowerCase()));
    }

    const matchesAnySearch = matchesSearch || matchesAlloc;
    if (!matchesAnySearch) return false;

    if (manifestFilter === 'allocated') {
      return !!activeAlloc;
    } else if (manifestFilter === 'unallocated') {
      return !activeAlloc;
    }
    return true; // 'all'
  });

  const filteredVehicles = vehicles.filter(v => {
    return (v.vehicle_number && v.vehicle_number.toLowerCase().includes(search.toLowerCase())) ||
      (v.vehicle_model && v.vehicle_model.toLowerCase().includes(search.toLowerCase())) ||
      (v.registration_number && v.registration_number.toLowerCase().includes(search.toLowerCase())) ||
      (v.vehicle_type && v.vehicle_type.toLowerCase().includes(search.toLowerCase()));
  });

  const filteredRoutes = routes.filter(r => {
    return (r.route_title && r.route_title.toLowerCase().includes(search.toLowerCase())) ||
      (r.code && r.code.toLowerCase().includes(search.toLowerCase())) ||
      (r.start_place && r.start_place.toLowerCase().includes(search.toLowerCase())) ||
      (r.end_place && r.end_place.toLowerCase().includes(search.toLowerCase()));
  });



  const filteredPickupPoints = pickupPoints.filter(p => p.route_id === parseInt(assignForm.route_id));
  const filteredVehicleRoutes = vehicleRoutes.filter(vr => vr.route_id === parseInt(assignForm.route_id));

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-24 sm:pb-10">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight uppercase">Transport Summary</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Logistics</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Fleet & Routing Network</span>
          </nav>
        </div>
        <div className="flex gap-3">
          {activeTab === 'fleet' && (
            <button onClick={() => setShowVehicleModal(true)} className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg active:scale-95">
              <Plus size={18} />
              Register Vehicle
            </button>
          )}
          {activeTab === 'routes' && (
            <button onClick={() => setShowRouteModal(true)} className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg active:scale-95">
              <Plus size={18} />
              Define Route
            </button>
          )}
          {activeTab === 'allocations' && (
            <button 
              onClick={() => {
                setAssignForm({
                  student_id: '',
                  route_id: '',
                  pickup_point_id: '',
                  vehicle_route_id: '',
                  fee_amount: '50',
                  effective_from: new Date().toISOString().split('T')[0],
                  effective_to: ''
                });
                setShowAssignModal(true);
              }} 
              className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg active:scale-95"
            >
              <Plus size={18} />
              Allocate Passenger
            </button>
          )}
        </div>
      </div>

      {/* Stats - FIXED: Now shows all 4 stats at all times */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 animate-in fade-in duration-300">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 group cursor-default">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center ${getStatColors(stat.color)} group-hover:scale-110 transition-transform`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <p className="text-2xl font-black text-text">{stat.value}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Tabs Control */}
      <div className="bg-card border border-border rounded-[2rem] p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
        <div className="flex p-1 bg-muted/50 rounded-2xl overflow-x-auto min-w-0 no-scrollbar">
          {[
            { id: 'fleet', label: 'Fleet Registry', icon: Bus },
            { id: 'routes', label: 'Routing Matrix', icon: Map },
            { id: 'allocations', label: 'Passenger Manifest', icon: Users },
            { id: 'attendance', label: 'Attendance', icon: ClipboardCheck },
            { id: 'history', label: 'History', icon: History },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`
                px-6 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all whitespace-nowrap flex items-center justify-center gap-2
                ${activeTab === tab.id ? 'bg-card text-primary shadow-sm ring-1 ring-border' : 'text-text-muted hover:text-text'}
              `}
            >
              <tab.icon size={14} />
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {/* Main Content */}
      <div className="min-h-[400px]" key={activeTab}>
        {loading ? (
          <div className="py-20 text-center">
            <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
            <p className="text-text-muted font-bold uppercase tracking-widest text-xs italic">Syncing Transport Summary...</p>
          </div>
        ) : activeTab === 'fleet' ? (
          <div className="space-y-6">
            <div className="flex flex-col md:flex-row justify-between items-stretch md:items-center gap-4">
              <div>
                <h3 className="text-lg font-black text-text uppercase tracking-wider">Fleet Registry</h3>
                <p className="text-xs text-text-muted">Manage active transport vehicles, models, and operators.</p>
              </div>
              <div className="relative md:w-80">
                <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
                <input 
                  type="text" 
                  className="w-full bg-card border border-border rounded-2xl pl-11 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:border-primary transition-all text-text"
                  placeholder="Search fleet registry..."
                  value={search}
                  onChange={e => setSearch(e.target.value)}
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
              {filteredVehicles.map(v => (
                <div key={v.id} className="bg-card border border-border rounded-[2.5rem] p-8 hover:shadow-xl transition-all group relative overflow-hidden flex flex-col">
                  <div className="flex justify-between items-start mb-6">
                    <div className="w-16 h-16 rounded-[1.5rem] bg-indigo-50 text-indigo-600 dark:bg-indigo-900/30 dark:text-indigo-400 flex items-center justify-center border border-indigo-100 dark:border-indigo-800 shadow-sm group-hover:scale-110 transition-transform">
                      <Bus size={32} />
                    </div>
                    <span className={`px-3 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${
                      v.status === 'active' ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-800' : 
                      v.status === 'maintenance' ? 'bg-orange-50 text-orange-600 border-orange-100 dark:bg-orange-900/20 dark:text-orange-400 dark:border-orange-800' :
                      'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-900/20 dark:text-rose-400 dark:border-rose-800'
                    }`}>
                      {v.status}
                    </span>
                  </div>
                  <div className="space-y-1 mb-6">
                    <h3 className="text-2xl font-black text-text tracking-tight group-hover:text-primary transition-colors">{v.vehicle_number}</h3>
                    <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-[3px]">{v.vehicle_model} | {v.vehicle_type}</p>
                  </div>
                  <div className="space-y-3 pt-6 border-t border-border flex-grow">
                      <div className="flex items-center gap-3 text-sm text-text-muted font-mono">
                          <Hash size={14} className="text-primary" /> REG: {v.registration_number}
                      </div>
                      <div className="flex items-center gap-3 text-sm text-text-muted">
                          <User size={14} className="text-primary" /> {v.driver_name || 'Unassigned Operator'}
                      </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ) : activeTab === 'routes' ? (
          <div className="space-y-6">
            <div className="flex flex-col md:flex-row justify-between items-stretch md:items-center gap-4">
              <div>
                <h3 className="text-lg font-black text-text uppercase tracking-wider">Active Routes</h3>
                <p className="text-xs text-text-muted">Explore and manage defined transit pathways and unit assignments.</p>
              </div>
              <div className="relative md:w-80">
                <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
                <input 
                  type="text" 
                  className="w-full bg-card border border-border rounded-2xl pl-11 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:border-primary transition-all text-text"
                  placeholder="Search routes, codes, places..."
                  value={search}
                  onChange={e => setSearch(e.target.value)}
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {filteredRoutes.map(r => (
                <div key={r.id} className="bg-card border border-border rounded-[2.5rem] p-8 hover:shadow-xl transition-all group flex flex-col relative overflow-hidden">
                  <div className="absolute top-0 right-0 w-32 h-32 bg-primary/5 rounded-bl-full -z-10 transition-transform group-hover:scale-110"></div>
                  
                  <div className="flex justify-between items-start mb-6 z-10">
                    <div className="w-14 h-14 rounded-[1.2rem] bg-primary/10 text-primary flex items-center justify-center">
                      <Navigation size={24} />
                    </div>
                    <div className="text-right">
                        <span className="px-3 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest bg-muted border border-border">
                            {r.distance} KM
                        </span>
                    </div>
                  </div>
                  
                  <div className="space-y-1 mb-8 z-10">
                    <h3 className="text-xl font-black text-text tracking-tight">{r.route_title}</h3>
                    <div className="flex justify-between items-center gap-4 mt-1">
                      <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-[3px]">Assigned Unit: {r.vehicle_number || 'Pending'} ({r.driver_name || 'N/A'})</p>
                      <button 
                        onClick={() => {
                          const currentVehicle = vehicles.find(v => v.registration_number === r.vehicle_number);
                          const currentDriver = drivers.find(d => d.full_name === r.driver_name);
                          setAssignUnitForm({
                            route_id: r.id.toString(),
                            vehicle_id: currentVehicle ? currentVehicle.id.toString() : '',
                            driver_id: currentDriver ? currentDriver.id.toString() : ''
                          });
                          setShowAssignUnitModal(true);
                        }}
                        className="px-2.5 py-1 border border-primary/20 hover:bg-primary/5 text-primary rounded-lg font-black text-[0.55rem] uppercase tracking-widest transition-all"
                      >
                        Assign Unit
                      </button>
                    </div>
                  </div>

                  <div className="bg-muted/30 rounded-2xl p-5 border border-border relative z-10 flex-grow">
                      <div className="relative border-l-2 border-primary/30 pl-4 space-y-6 ml-2">
                          <div className="relative">
                              <div className="absolute -left-[23px] top-1 w-3 h-3 rounded-full bg-primary ring-4 ring-primary/20"></div>
                              <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">Origin Point</p>
                              <p className="text-sm font-bold text-text mt-1">{r.start_place}</p>
                          </div>
                          <div className="relative">
                              <div className="absolute -left-[23px] top-1 w-3 h-3 rounded-full bg-rose-500 ring-4 ring-rose-500/20"></div>
                              <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">Terminal Point</p>
                              <p className="text-sm font-bold text-text mt-1">{r.end_place}</p>
                          </div>
                      </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ) : activeTab === 'attendance' ? (
          <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
            <AttendanceTakeView initialContext="transport" showTabs={false} />
          </div>
        ) : activeTab === 'history' ? (
          <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
            <AttendanceHistoryView studentOptions={students} tabs={['transport']} />
          </div>
        ) : (
          <div className="space-y-6">
            <div className="flex flex-col md:flex-row justify-between items-stretch md:items-center gap-4">
              <div className="flex flex-wrap gap-2">
                {[
                  { id: 'allocated', label: 'Allocated Passengers' },
                  { id: 'unallocated', label: 'Unallocated Students' },
                  { id: 'all', label: 'All Students' },
                ].map(f => (
                  <button
                    key={f.id}
                    onClick={() => setManifestFilter(f.id as any)}
                    className={`px-5 py-2.5 rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all border ${
                      manifestFilter === f.id
                        ? 'bg-primary/10 border-primary/30 text-primary shadow-sm'
                        : 'bg-card border-border text-text-muted hover:text-text'
                    }`}
                  >
                    {f.label}
                  </button>
                ))}
              </div>

              <div className="relative md:w-80">
                <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
                <input 
                  type="text" 
                  className="w-full bg-card border border-border rounded-2xl pl-11 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:border-primary transition-all text-text"
                  placeholder="Search passenger, class, route, stop, unit..."
                  value={search}
                  onChange={e => setSearch(e.target.value)}
                />
              </div>
            </div>

            <div className="bg-card border border-border rounded-[2.5rem] overflow-hidden shadow-sm">
              <div className="overflow-x-auto">
                <table className="w-full text-left">
                  <thead>
                    <tr className="bg-muted/50 border-b border-border">
                      <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Passenger Profile</th>
                      <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Routing Assignment</th>
                      <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Designated Stop</th>
                      <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {filteredStudents.map(s => {
                      const activeAlloc = allocations.find(a => a.student_id === s.id && a.status === 'active');
                      const initials = s.full_name.split(' ').map((n: string) => n[0]).join('').toUpperCase().substring(0, 2);
                      return (
                        <tr key={s.id} className="hover:bg-muted/30 transition-colors">
                          <td className="px-8 py-5">
                            <div className="flex items-center gap-4">
                              <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary font-black text-sm uppercase">
                                {initials}
                              </div>
                              <div>
                                <p className="text-sm font-bold text-text">{s.full_name}</p>
                                <p className="text-[0.6rem] text-text-muted font-black tracking-widest uppercase mt-0.5">
                                  {activeAlloc ? `PASSENGER ID: ${activeAlloc.uid.substring(0, 8)}` : `CLASS: ${s.class_name || 'N/A'}`}
                                </p>
                              </div>
                            </div>
                          </td>
                          <td className="px-8 py-5">
                            {activeAlloc ? (
                              <>
                                <p className="text-xs font-bold text-text">{activeAlloc.route_title}</p>
                                <p className="text-[0.6rem] text-text-muted font-black tracking-widest uppercase mt-1">UNIT: {activeAlloc.vehicle_number || 'Pending'}</p>
                              </>
                            ) : (
                              <span className="px-2.5 py-1 rounded-lg text-[0.55rem] font-black uppercase tracking-widest border bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-900/20 dark:text-rose-400 dark:border-rose-800/50">
                                Unallocated
                              </span>
                            )}
                          </td>
                          <td className="px-8 py-5">
                            {activeAlloc ? (
                              <span className="text-sm font-bold text-text flex items-center gap-2">
                                  <MapPin size={14} className="text-rose-500" /> {activeAlloc.stop_name || 'Main Route Stop'}
                              </span>
                            ) : (
                              <span className="text-text-muted/40 font-bold">—</span>
                            )}
                          </td>
                          <td className="px-8 py-5 text-right">
                            {activeAlloc ? (
                              <button
                                onClick={async () => {
                                  if (window.confirm(`Are you sure you want to deallocate ${s.full_name}?`)) {
                                    try {
                                      await deallocateTransport(activeAlloc.id);
                                    } catch (err) {
                                      console.error('Error deallocating:', err);
                                    }
                                  }
                                }}
                                className="px-4 py-2 border border-rose-500/20 text-rose-500 hover:bg-rose-500/10 rounded-lg font-black text-[0.6rem] uppercase tracking-widest transition-all"
                              >
                                Deallocate
                              </button>
                            ) : (
                              <button 
                                onClick={() => {
                                  setAssignForm({
                                    student_id: s.id.toString(),
                                    route_id: '',
                                    pickup_point_id: '',
                                    vehicle_route_id: '',
                                    fee_amount: '50',
                                    effective_from: new Date().toISOString().split('T')[0],
                                    effective_to: ''
                                  });
                                  setShowAssignModal(true);
                                }}
                                className="px-4 py-2 bg-primary text-white hover:bg-primary/95 rounded-lg font-black text-[0.6rem] uppercase tracking-widest transition-all shadow-md active:scale-95"
                              >
                                Allocate Route
                              </button>
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Register Vehicle Modal */}
      {showVehicleModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => setShowVehicleModal(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 max-h-[90vh] flex flex-col border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0 dark:bg-background/50">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <Bus size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">Register Vehicle</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Register vehicle details</p>
              </div>
              <button 
                className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm" 
                onClick={closeVehicleModal}
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleAddVehicle} className="p-10 space-y-6 overflow-y-auto flex-1 custom-scrollbar">
              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Reg Number*</label>
                  <input
                    required
                    type="text"
                    placeholder="e.g. AB-1234"
                    value={vehicleForm.registration_number}
                    onChange={e => setVehicleForm({ ...vehicleForm, registration_number: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Model*</label>
                  <input
                    required
                    type="text"
                    placeholder="e.g. Toyota Coaster"
                    value={vehicleForm.model}
                    onChange={e => setVehicleForm({ ...vehicleForm, model: e.target.value })}
                    className="form-input"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Capacity*</label>
                  <input
                    required
                    type="number"
                    min={1}
                    value={vehicleForm.capacity}
                    onChange={e => setVehicleForm({ ...vehicleForm, capacity: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Type*</label>
                  <select
                    value={vehicleForm.vehicle_type}
                    onChange={e => setVehicleForm({ ...vehicleForm, vehicle_type: e.target.value })}
                    className="form-input"
                  >
                    <option value="bus">Bus</option>
                    <option value="minibus">Mini-Bus</option>
                    <option value="van">Van</option>
                    <option value="car">Car</option>
                    <option value="other">Other</option>
                  </select>
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Fuel Type*</label>
                <select
                  value={vehicleForm.fuel_type}
                  onChange={e => setVehicleForm({ ...vehicleForm, fuel_type: e.target.value })}
                  className="form-input"
                >
                  <option value="Diesel">Diesel</option>
                  <option value="Petrol">Petrol</option>
                  <option value="Electric">Electric</option>
                  <option value="Hybrid">Hybrid</option>
                </select>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Description</label>
                <textarea
                  rows={2}
                  placeholder="Notes about vehicle schedule or maintenance..."
                  value={vehicleForm.description}
                  onChange={e => setVehicleForm({ ...vehicleForm, description: e.target.value })}
                  className="form-input resize-none"
                />
              </div>

              <button 
                type="submit" 
                className="w-full py-5 bg-primary hover:bg-primary-dark text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3 shadow-primary/20"
              >
                <Sparkles size={18} />
                Register Vehicle Asset
              </button>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {/* Define Route Modal */}
      {showRouteModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => setShowRouteModal(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 max-h-[90vh] flex flex-col border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0 dark:bg-background/50">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <Map size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">Define Route</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Configure path and assignments</p>
              </div>
              <button 
                className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm" 
                onClick={closeRouteModal}
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleAddRoute} className="p-10 space-y-6 overflow-y-auto flex-1 custom-scrollbar">
              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Route Name*</label>
                  <input
                    required
                    type="text"
                    placeholder="e.g. Route A"
                    value={routeForm.name}
                    onChange={e => setRouteForm({ ...routeForm, name: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Code*</label>
                  <input
                    required
                    type="text"
                    placeholder="e.g. R-101"
                    value={routeForm.code}
                    onChange={e => setRouteForm({ ...routeForm, code: e.target.value })}
                    className="form-input"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Start Point*</label>
                  <input
                    required
                    type="text"
                    placeholder="e.g. North Campus"
                    value={routeForm.start_point}
                    onChange={e => setRouteForm({ ...routeForm, start_point: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">End Point*</label>
                  <input
                    required
                    type="text"
                    placeholder="e.g. East Suburb"
                    value={routeForm.end_point}
                    onChange={e => setRouteForm({ ...routeForm, end_point: e.target.value })}
                    className="form-input"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Distance (KM)*</label>
                  <input
                    required
                    type="number"
                    step="0.1"
                    min={0.1}
                    value={routeForm.distance_km}
                    onChange={e => setRouteForm({ ...routeForm, distance_km: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Time (Mins)*</label>
                  <input
                    required
                    type="number"
                    min={1}
                    value={routeForm.estimated_time_minutes}
                    onChange={e => setRouteForm({ ...routeForm, estimated_time_minutes: e.target.value })}
                    className="form-input"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Vehicle (Bus)</label>
                  <SearchableSelect
                    options={vehicles.map(v => ({ value: v.id, label: `${v.registration_number} - ${v.vehicle_model}` }))}
                    value={routeForm.vehicle_id}
                    onChange={val => setRouteForm({ ...routeForm, vehicle_id: val.toString() })}
                    placeholder="-- Assign Bus (Optional) --"
                    className="w-full"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Driver</label>
                  <SearchableSelect
                    options={drivers.map(d => ({ value: d.id, label: d.full_name }))}
                    value={routeForm.driver_id}
                    onChange={val => setRouteForm({ ...routeForm, driver_id: val.toString() })}
                    placeholder="-- Assign Driver (Optional) --"
                    className="w-full"
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Description</label>
                <textarea
                  rows={2}
                  placeholder="Notes about schedule, landmarks..."
                  value={routeForm.description}
                  onChange={e => setRouteForm({ ...routeForm, description: e.target.value })}
                  className="form-input resize-none"
                />
              </div>

              <button 
                type="submit" 
                className="w-full py-5 bg-primary hover:bg-primary-dark text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3 shadow-primary/20"
              >
                <Sparkles size={18} />
                Create Route Definition
              </button>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {/* Allocate Transport Modal */}
      {showAssignModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => setShowAssignModal(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 max-h-[90vh] flex flex-col border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0 dark:bg-background/50">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <Users size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">Allocate Transport</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Passenger Assignment</p>
              </div>
              <button 
                className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm" 
                onClick={closeAssignModal}
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleAllocateTransport} className="p-10 space-y-6 overflow-y-auto flex-1 custom-scrollbar">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Select Resident Student*</label>
                <SearchableSelect
                  options={students.map(s => ({ value: s.id, label: `${s.full_name} (${s.class_name || 'No Class'})` }))}
                  value={assignForm.student_id}
                  onChange={val => setAssignForm({ ...assignForm, student_id: val.toString() })}
                  placeholder="-- Choose Student --"
                  className="w-full"
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Select Route*</label>
                <SearchableSelect
                  options={routes.map(r => ({ value: r.id, label: `${r.route_title} (${r.code || ''})` }))}
                  value={assignForm.route_id}
                  onChange={val => {
                    setAssignForm({
                      ...assignForm,
                      route_id: val.toString(),
                      pickup_point_id: '',
                      vehicle_route_id: ''
                    });
                  }}
                  placeholder="-- Choose Route --"
                  className="w-full"
                />
              </div>

              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Pickup Stop</label>
                  <select
                    value={assignForm.pickup_point_id}
                    onChange={e => setAssignForm({ ...assignForm, pickup_point_id: e.target.value })}
                    className="form-input"
                    disabled={!assignForm.route_id}
                  >
                    <option value="">-- Select Stop (Optional) --</option>
                    {filteredPickupPoints.map(p => (
                      <option key={p.id} value={p.id}>{p.name} ({p.pickup_time})</option>
                    ))}
                  </select>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Vehicle / Driver Unit</label>
                  <select
                    value={assignForm.vehicle_route_id}
                    onChange={e => setAssignForm({ ...assignForm, vehicle_route_id: e.target.value })}
                    className="form-input"
                    disabled={!assignForm.route_id}
                  >
                    <option value="">-- Select Operator (Optional) --</option>
                    {filteredVehicleRoutes.map(vr => (
                      <option key={vr.id} value={vr.id}>Unit: {vr.vehicle_number || 'Pending'} - Driver: {vr.driver_name || 'N/A'} ({vr.start_time || 'N/A'})</option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Fee Amount*</label>
                  <input
                    required
                    type="number"
                    min={0}
                    value={assignForm.fee_amount}
                    onChange={e => setAssignForm({ ...assignForm, fee_amount: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Effective Date*</label>
                  <input
                    required
                    type="date"
                    value={assignForm.effective_from}
                    onChange={e => setAssignForm({ ...assignForm, effective_from: e.target.value })}
                    className="form-input"
                  />
                </div>
              </div>

              <button 
                type="submit" 
                className="w-full py-5 bg-primary hover:bg-primary-dark text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3 shadow-primary/20"
              >
                <Sparkles size={18} />
                Confirm Allocation
              </button>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {/* Assign Route Unit Modal */}
      {showAssignUnitModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => setShowAssignUnitModal(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 max-h-[90vh] flex flex-col border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0 dark:bg-background/50">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <Navigation size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">Assign Route Unit</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">
                  Route: {routes.find(r => r.id === parseInt(assignUnitForm.route_id))?.route_title || 'Selected Route'}
                </p>
              </div>
              <button 
                className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm" 
                onClick={() => setShowAssignUnitModal(false)}
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={async (e) => {
              e.preventDefault();
              try {
                await assignRouteUnit(
                  parseInt(assignUnitForm.route_id),
                  assignUnitForm.vehicle_id ? parseInt(assignUnitForm.vehicle_id) : null,
                  assignUnitForm.driver_id ? parseInt(assignUnitForm.driver_id) : null
                );
                setShowAssignUnitModal(false);
              } catch (err) {
                console.error('Error assigning route unit:', err);
              }
            }} className="p-10 space-y-6 overflow-y-auto flex-1 custom-scrollbar">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Select Vehicle (Bus)*</label>
                <select
                  required
                  value={assignUnitForm.vehicle_id}
                  onChange={e => setAssignUnitForm({ ...assignUnitForm, vehicle_id: e.target.value })}
                  className="form-input"
                >
                  <option value="">-- Select Bus --</option>
                  {vehicles.map(v => (
                    <option key={v.id} value={v.id}>{v.registration_number} - {v.vehicle_model} (Cap: {v.capacity})</option>
                  ))}
                </select>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Select Driver*</label>
                <select
                  required
                  value={assignUnitForm.driver_id}
                  onChange={e => setAssignUnitForm({ ...assignUnitForm, driver_id: e.target.value })}
                  className="form-input"
                >
                  <option value="">-- Select Driver --</option>
                  {drivers.map(d => (
                    <option key={d.id} value={d.id}>{d.full_name}</option>
                  ))}
                </select>
              </div>

              <button 
                type="submit" 
                className="w-full py-5 bg-primary hover:bg-primary-dark text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3 shadow-primary/20"
              >
                <Sparkles size={18} />
                Assign Route Unit
              </button>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
      `}</style>
    </div>
  );
}