import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Clock, 
  Plus, 
  User, 
  Stethoscope, 
  Car,
  X,
  Loader2,
  Check,
  AlertCircle,
  Activity,
  Calendar
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { fleetApi } from '../../api/fleet';

// --- INTERFACES ---
interface Assignment {
  id: string;
  date: string; // YYYY-MM-DD
  vehicleId: string;
  vehicleReg?: string;
  vehicleType: 'ALS' | 'BLS' | 'TRANS';
  shift: 'MORNING' | 'EVENING' | 'NIGHT';
  driver: string;
  emt: string;
  doctor?: string;
  status: 'SCHEDULED' | 'ON_DUTY';
  startTime: string;
  endTime: string;
}

interface APIVehicle {
  id: string;
  registration_number: string;
  vehicle_type: string;
  status?: string;
}

interface APIStaff {
  id: string;
  type: string;
  status?: string;
  user?: {
    name?: string;
    phone?: string;
  };
}

const SHIFTS = [
  { key: 'MORNING', label: 'Morning', time: '06:00 – 14:00', color: '#F59E0B', bg: 'rgba(245,158,11,0.1)' },
  { key: 'EVENING', label: 'Evening', time: '14:00 – 22:00', color: '#3B82F6', bg: 'rgba(59,130,246,0.1)' },
  { key: 'NIGHT',   label: 'Night',   time: '22:00 – 06:00', color: '#8B5CF6', bg: 'rgba(139,92,246,0.1)' },
] as const;

export const FleetScheduling: React.FC = () => {
  const navigate = useNavigate();
  // --- STATE ---
  const [selectedDate] = useState<string>(new Date().toISOString().split('T')[0]);
  const [view, setView] = useState<'DAY' | 'WEEK' | 'MONTH'>('DAY');

  // Roster lists & API state
  const [apiVehicles, setApiVehicles] = useState<APIVehicle[]>([]);
  const [apiStaff, setApiStaff] = useState<APIStaff[]>([]);
  const [loadingAssets, setLoadingAssets] = useState(false);
  const [submittingRoster, setSubmittingRoster] = useState(false);
  const [rosterSuccess, setRosterSuccess] = useState('');
  const [rosterErr, setRosterErr] = useState('');

  const [assignments, setAssignments] = useState<Assignment[]>([]);

  // Modals state
  const [showCreateModal, setShowCreateModal] = useState(false);

  // Form states for creating dynamic Roster
  const [formVehicleId, setFormVehicleId] = useState('');
  const [formDriverId, setFormDriverId] = useState('');
  const [formStaffId, setFormStaffId] = useState('');
  const [formStartDate, setFormStartDate] = useState('');
  const [formEndDate, setFormEndDate] = useState('');
  const [formShiftType, setFormShiftType] = useState<'DAY' | 'NIGHT' | 'SPLIT' | ''>('');
  const [formNotes, setFormNotes] = useState('');

  const token = localStorage.getItem('teleems_token') || '';

  // --- FETCH OPERATOR ASSETS (Vehicles & Staff) ---
  const fetchAssets = useCallback(async () => {
    if (!token) return;
    setLoadingAssets(true);
    try {
      // 1. Fetch Vehicles
      const vJson = await fleetApi.getVehicles(token);
      let vList: APIVehicle[] = [];
      if (vJson?.data?.data && Array.isArray(vJson.data.data)) vList = vJson.data.data;
      else if (vJson?.data && Array.isArray(vJson.data)) vList = vJson.data;
      else if (Array.isArray(vJson)) vList = vJson;
      setApiVehicles(vList);

      // 2. Fetch Staff
      const sJson = await fleetApi.getStaff(token);
      let sList: APIStaff[] = [];
      if (sJson?.data?.data && Array.isArray(sJson.data.data)) sList = sJson.data.data;
      else if (sJson?.data && Array.isArray(sJson.data)) sList = sJson.data;
      else if (Array.isArray(sJson)) sList = sJson;
      setApiStaff(sList);

      // 3. Fetch Scheduled Rosters
      let rList: any[] = [];
      try {
        const rJson = await fleetApi.getRoster(token);
        if (rJson) {
          rList = rJson?.data?.data || rJson?.data || (Array.isArray(rJson) ? rJson : []);
        }
      } catch (err) {
        console.error('Failed to fetch roster list:', err);
      }

      // 4. Map to assignments (using actual data only, completely removing mocks)
      const parsedAssignments: Assignment[] = [];
      const addedIds = new Set<string>();

      // Add from roster query
      rList.forEach((r: any) => {
        if (!r.id) return;
        const vehicle = r.vehicle || vList.find((v: any) => v.id === r.vehicleId);
        const driverName = r.driver?.user?.name || 'Unknown Pilot';
        const staffName = r.staff?.user?.name || 'Unknown EMT';
        
        parsedAssignments.push({
          id: r.id,
          date: r.startDate || new Date().toISOString().split('T')[0],
          vehicleId: r.vehicleId,
          vehicleReg: vehicle?.registration_number || r.vehicleId,
          vehicleType: (vehicle?.vehicle_type as any) || 'ALS',
          shift: r.shiftType === 'NIGHT' ? 'NIGHT' : (r.shiftType === 'DAY' ? 'MORNING' : 'EVENING'),
          driver: driverName,
          emt: staffName,
          status: 'SCHEDULED',
          startTime: r.shiftType === 'NIGHT' ? '22:00' : (r.shiftType === 'DAY' ? '06:00' : '14:00'),
          endTime: r.shiftType === 'NIGHT' ? '06:00' : (r.shiftType === 'DAY' ? '14:00' : '22:00')
        });
        addedIds.add(r.id);
      });

      // Add active rosters from live vehicles list
      vList.forEach((v: any) => {
        if (v.activeRoster && v.activeRoster.id && !addedIds.has(v.activeRoster.id)) {
          const r = v.activeRoster;
          const driverName = r.driver?.user?.name || 'Unknown Pilot';
          const staffName = r.staff?.user?.name || 'Unknown EMT';
          
          parsedAssignments.push({
            id: r.id,
            date: new Date().toISOString().split('T')[0],
            vehicleId: v.id,
            vehicleReg: v.registration_number,
            vehicleType: (v.vehicle_type as any) || 'ALS',
            shift: 'MORNING',
            driver: driverName,
            emt: staffName,
            status: 'ON_DUTY',
            startTime: '06:00',
            endTime: '14:00'
          });
          addedIds.add(r.id);
        }

        if (v.activeShift && v.activeShift.id && !addedIds.has(v.activeShift.id)) {
          const sh = v.activeShift;
          const driverName = sh.driver?.user?.name || 'Unknown Pilot';
          const staffName = sh.staff?.user?.name || 'Unknown EMT';
          
          parsedAssignments.push({
            id: sh.id,
            date: new Date().toISOString().split('T')[0],
            vehicleId: v.id,
            vehicleReg: v.registration_number,
            vehicleType: (v.vehicle_type as any) || 'ALS',
            shift: 'EVENING',
            driver: driverName,
            emt: staffName,
            status: 'ON_DUTY',
            startTime: '14:00',
            endTime: '22:00'
          });
          addedIds.add(sh.id);
        }
      });

      setAssignments(parsedAssignments);

    } catch (e) {
      console.error('[Scheduling API Check] Failed to sync assets:', e);
    } finally {
      setLoadingAssets(false);
    }
  }, [token]);

  useEffect(() => {
    fetchAssets();
  }, [fetchAssets]);

  const driverOptions = useMemo(() => {
    return apiStaff.filter(s => s.type === 'DRIVER').map(s => ({ id: s.id, name: s.user?.name || 'Unknown Pilot' }));
  }, [apiStaff]);

  const emtOptions = useMemo(() => {
    return apiStaff.filter(s => s.type === 'EMT').map(s => ({ id: s.id, name: s.user?.name || 'Unknown EMT' }));
  }, [apiStaff]);

  const doctorOptions = useMemo(() => {
    return apiStaff.filter(s => s.type === 'DOCTOR').map(s => ({ id: s.id, name: s.user?.name || 'Unknown Doctor' }));
  }, [apiStaff]);

  const vehicleOptions = useMemo(() => {
    return apiVehicles.map(v => ({ id: v.id, registration_number: v.registration_number, vehicle_type: v.vehicle_type || 'ALS' }));
  }, [apiVehicles]);

  const currentFilteredAssignments = useMemo(() => {
    return assignments.filter(as => {
      if (view === 'DAY') {
        return as.date === selectedDate;
      } else if (view === 'WEEK') {
        const dateDiff = Math.abs(new Date(as.date).getTime() - new Date(selectedDate).getTime());
        const daysDiff = dateDiff / (1000 * 3600 * 24);
        return daysDiff <= 3;
      } else {
        return as.date.substring(0, 7) === selectedDate.substring(0, 7);
      }
    });
  }, [assignments, selectedDate, view]);

  const openCreateModal = () => {
    setFormVehicleId('');
    setFormDriverId('');
    setFormStaffId('');
    setFormStartDate('');
    setFormEndDate('');
    setFormShiftType('');
    setFormNotes('');
    setRosterErr('');
    setRosterSuccess('');
    setShowCreateModal(true);
  };

  const handleCreateAssignment = async () => {
    setRosterErr('');
    setRosterSuccess('');

    if (!formVehicleId) {
      setRosterErr('Please select an Ambulance Unit.');
      return;
    }
    if (!formShiftType) {
      setRosterErr('Please select a Shift Type.');
      return;
    }
    if (!formDriverId) {
      setRosterErr('Please select a Driver.');
      return;
    }
    if (!formStaffId) {
      setRosterErr('Please select a Staff Member (EMT/Doctor).');
      return;
    }
    if (!formStartDate || !formEndDate) {
      setRosterErr('Please select both Start Date and End Date.');
      return;
    }

    const isUuid = (str: string) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(str);

    if (!isUuid(formVehicleId) || !isUuid(formDriverId) || !isUuid(formStaffId)) {
      setRosterErr('Selected items must be valid backend UUIDs. Please register assets first.');
      return;
    }

    const payload = {
      vehicleId: formVehicleId,
      driverId: formDriverId,
      staffId: formStaffId,
      startDate: formStartDate,
      endDate: formEndDate,
      shiftType: formShiftType,
      notes: formNotes || 'Fleet Deployment Roster'
    };

    setSubmittingRoster(true);
    try {
      const json = await fleetApi.createRoster(payload, token);

      if (json && json.status && json.status >= 400) {
        throw new Error(json?.message || `API Response Error ${json.status}`);
      }

      setRosterSuccess('Roster scheduled successfully on backend API!');

      setTimeout(() => {
        fetchAssets(); // Refresh assignments from real database endpoints
        setShowCreateModal(false);
        setRosterSuccess('');
      }, 1500);

    } catch (err: any) {
      console.error('[Create Roster Error]:', err);
      setRosterErr(err?.message || 'Failed to schedule roster assignment on backend.');
    } finally {
      setSubmittingRoster(false);
    }
  };

  return (
    <div style={{ color: '#F8FAFC', fontFamily: 'Inter, sans-serif' }}>

      {/* ── Header Toolbar (View selection controls & create button) ── */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24, flexWrap: 'wrap', gap: 12 }}>
        
        {/* View Mode Toggle (Daily, Weekly, Monthly) */}
        <div style={{ display: 'flex', gap: 4, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 10, padding: 3 }}>
          {(['DAY', 'WEEK', 'MONTH'] as const).map(v => (
            <button key={v} onClick={() => setView(v)}
              style={{ padding: '8px 16px', borderRadius: 8, border: 'none', fontSize: '0.78rem', fontWeight: 700, cursor: 'pointer', background: view === v ? 'linear-gradient(135deg,#06B6D4,#3B82F6)' : 'transparent', color: view === v ? '#fff' : '#64748B', transition: 'all 0.2s' }}>
              {v === 'DAY' ? 'Daily' : v === 'WEEK' ? 'Weekly' : 'Monthly'}
            </button>
          ))}
        </div>

        {/* Action Buttons */}
        <div style={{ display: 'flex', gap: 10 }}>
          <button onClick={() => navigate('?tab=active-shifts')} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 12px', background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 10, color: '#10B981', fontSize: '0.75rem', fontWeight: 700, cursor: 'pointer' }}>
            <Activity size={13} /> Active Shifts
          </button>
          <button onClick={fetchAssets} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 12px', background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 10, color: '#94A3B8', fontSize: '0.75rem', fontWeight: 700, cursor: 'pointer' }}>
            {loadingAssets ? <Loader2 size={13} className="spin" /> : '↺ Sync Assets'}
          </button>
          <button onClick={openCreateModal} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 20px', background: 'linear-gradient(135deg,#06B6D4,#3B82F6)', border: 'none', borderRadius: 12, color: '#fff', fontWeight: 800, fontSize: '0.82rem', cursor: 'pointer', boxShadow: '0 4px 14px rgba(6,182,212,0.3)', whiteSpace: 'nowrap' }}>
            <Plus size={16} /> NEW CREW ASSIGNMENT
          </button>
        </div>

      </div>

      {/* ── Roster Grid ── */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        
        {/* Count summary label */}
        <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
          <span style={{ fontSize: '0.75rem', color: '#64748B' }}>
            Showing {currentFilteredAssignments.length} scheduled slots ({view === 'DAY' ? 'Today' : view === 'WEEK' ? 'Weekly Outlook' : 'Monthly'})
          </span>
        </div>

        {/* Assignments Roster List */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {currentFilteredAssignments.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '64px 24px', background: 'rgba(255,255,255,0.01)', border: '1px dashed rgba(255,255,255,0.08)', borderRadius: 16 }}>
              <Calendar size={36} color="#64748B" style={{ marginBottom: 12 }} />
              <p style={{ color: '#64748B', fontSize: '0.88rem', margin: 0 }}>No crew roster scheduled for the selected view criteria.</p>
            </div>
          ) : (
            currentFilteredAssignments.map((a, i) => {
              const sh = SHIFTS.find(s => s.key === a.shift) || SHIFTS[0];

              return (
                <motion.div key={a.id} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.04 }}
                  style={{ 
                    background: 'rgba(255,255,255,0.02)', 
                    border: '1px solid rgba(255,255,255,0.07)', 
                    borderRadius: 16, 
                    padding: '18px 24px', 
                  }}
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                      {/* Vehicle identifier */}
                      <div style={{ padding: '6px 12px', background: 'linear-gradient(135deg, rgba(6,182,212,0.15), rgba(59,130,246,0.15))', border: '1px solid rgba(6,182,212,0.3)', borderRadius: 9, display: 'flex', alignItems: 'center', gap: 7, boxShadow: '0 0 10px rgba(6,182,212,0.1)' }}>
                        <Car size={14} color="#22D3EE" />
                        <span style={{ fontWeight: 900, fontSize: '0.85rem', color: '#22D3EE', letterSpacing: '0.5px' }}>{a.vehicleReg || a.vehicleId}</span>
                        <span style={{ fontSize: '0.65rem', fontWeight: 800, color: '#0F172A', background: '#22D3EE', padding: '2px 8px', borderRadius: 5 }}>{a.vehicleType}</span>
                      </div>
                      
                      {/* Shift Badge */}
                      <div style={{ padding: '5px 10px', background: sh.bg, border: `1px solid ${sh.color}30`, borderRadius: 7, display: 'flex', alignItems: 'center', gap: 6 }}>
                        <Clock size={11} color={sh.color} />
                        <span style={{ fontSize: '0.7rem', fontWeight: 700, color: sh.color }}>{sh.label} Shift</span>
                        <span style={{ fontSize: '0.65rem', color: sh.color, opacity: 0.8 }}>{a.startTime}–{a.endTime}</span>
                      </div>
                      
                      {/* Date details */}
                      <div style={{ fontSize: '0.72rem', fontWeight: 600, color: '#64748B', display: 'flex', alignItems: 'center', gap: 4 }}>
                        <Calendar size={12} /> {a.date}
                      </div>
                    </div>
                  </div>

                  {/* Driver + EMT (+ doctor if ALS) mapping */}
                  <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', background: 'rgba(6,182,212,0.04)', border: '1px solid rgba(6,182,212,0.08)', borderRadius: 12, flex: 1, minWidth: 200 }}>
                      <User size={15} color="#06B6D4" />
                      <div>
                        <div style={{ fontSize: '0.58rem', color: '#64748B', textTransform: 'uppercase', letterSpacing: '0.5px', fontWeight: 700 }}>Pilot Driver</div>
                        <div style={{ fontSize: '0.85rem', fontWeight: 700, color: '#000000' }}>{a.driver}</div>
                      </div>
                    </div>

                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', background: 'rgba(59,130,246,0.04)', border: '1px solid rgba(59,130,246,0.08)', borderRadius: 12, flex: 1, minWidth: 200 }}>
                      <Activity size={15} color="#3B82F6" />
                      <div>
                        <div style={{ fontSize: '0.58rem', color: '#64748B', textTransform: 'uppercase', letterSpacing: '0.5px', fontWeight: 700 }}>Emergency Medical Technician (EMT)</div>
                        <div style={{ fontSize: '0.85rem', fontWeight: 700, color: '#000000' }}>{a.emt}</div>
                      </div>
                    </div>

                    {a.vehicleType === 'ALS' && (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', background: 'rgba(16,185,129,0.04)', border: '1px solid rgba(16,185,129,0.08)', borderRadius: 12, flex: 1, minWidth: 200 }}>
                        <Stethoscope size={15} color="#10B981" />
                        <div>
                          <div style={{ fontSize: '0.58rem', color: '#64748B', textTransform: 'uppercase', letterSpacing: '0.5px', fontWeight: 700 }}>Advanced Medical Doctor</div>
                          <div style={{ fontSize: '0.85rem', fontWeight: 700, color: '#000000' }}>{a.doctor || 'Dr. Alok Mehta'}</div>
                        </div>
                      </div>
                    )}
                  </div>
                </motion.div>
              );
            })
          )}
        </div>
      </div>

      {/* ── CREATE ROSTER ASSIGNMENT MODAL ── */}
      <AnimatePresence>
        {showCreateModal && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)', zIndex: 3000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20, backdropFilter: 'blur(6px)' }}
            onClick={e => { if (e.target === e.currentTarget && !submittingRoster) setShowCreateModal(false); }}
          >
            <motion.div initial={{ scale: 0.93, y: 20, opacity: 0 }} animate={{ scale: 1, y: 0, opacity: 1 }} exit={{ scale: 0.93, y: 20, opacity: 0 }}
              style={{ background: '#0D1526', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 24, width: 620, maxWidth: '95vw', position: 'relative' }}
            >
              <div style={{ background: 'linear-gradient(135deg,rgba(6,182,212,0.12),transparent)', borderBottom: '1px solid rgba(255,255,255,0.07)', padding: '20px 28px 16px', borderRadius: '24px 24px 0 0' }}>
                <button onClick={() => setShowCreateModal(false)} disabled={submittingRoster} style={{ position: 'absolute', top: 14, right: 14, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, padding: 6, color: '#94A3B8', cursor: 'pointer', display: 'flex' }}><X size={15} /></button>
                <h3 style={{ margin: 0, fontSize: '1.05rem', fontWeight: 900, color: '#fff' }}>Deploy & Roster Crew</h3>
                <p style={{ margin: '4px 0 0', fontSize: '0.75rem', color: '#64748B' }}>Assign Driver + EMT (+ Doctor if ALS) to a vehicle for a shift</p>
              </div>

              <div style={{ padding: '20px 28px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
                
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  {/* Vehicle select */}
                  <div>
                    <label style={{ fontSize: '0.65rem', color: '#64748B', textTransform: 'uppercase', letterSpacing: '1px', fontWeight: 700, display: 'block', marginBottom: 6 }}>Ambulance Unit</label>
                    <select value={formVehicleId} onChange={e => setFormVehicleId(e.target.value)}
                      style={{ width: '100%', padding: '10px 14px', background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 10, color: '#fff', fontSize: '0.85rem', outline: 'none' }}>
                      <option value="" style={{ background: '#0D1526' }}>Select Ambulance</option>
                      {vehicleOptions.map(v => (
                        <option key={v.id} value={v.id} style={{ background: '#0D1526' }}>{v.registration_number} ({v.vehicle_type})</option>
                      ))}
                    </select>
                  </div>

                  {/* Shift Selection */}
                  <div>
                    <label style={{ fontSize: '0.65rem', color: '#64748B', textTransform: 'uppercase', letterSpacing: '1px', fontWeight: 700, display: 'block', marginBottom: 6 }}>Shift Type</label>
                    <select value={formShiftType} onChange={e => setFormShiftType(e.target.value as any)}
                      style={{ width: '100%', padding: '10px 14px', background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 10, color: '#fff', fontSize: '0.85rem', outline: 'none' }}>
                      <option value="" style={{ background: '#0D1526' }}>-- Select Shift Type --</option>
                      <option value="DAY" style={{ background: '#0D1526' }}>DAY (Morning/Evening)</option>
                      <option value="NIGHT" style={{ background: '#0D1526' }}>NIGHT (Night Shift)</option>
                      <option value="SPLIT" style={{ background: '#0D1526' }}>SPLIT (On-Demand)</option>
                    </select>
                  </div>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  {/* Driver deploy */}
                  <div>
                    <label style={{ fontSize: '0.65rem', color: '#64748B', textTransform: 'uppercase', letterSpacing: '1px', fontWeight: 700, display: 'block', marginBottom: 6 }}>Assign Driver</label>
                    <select value={formDriverId} onChange={e => setFormDriverId(e.target.value)}
                      style={{ width: '100%', padding: '10px 14px', background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 10, color: '#fff', fontSize: '0.85rem', outline: 'none' }}>
                      <option value="" style={{ background: '#0D1526' }}>-- Select Driver --</option>
                      {driverOptions.map(d => (
                        <option key={d.id} value={d.id} style={{ background: '#0D1526' }}>{d.name}</option>
                      ))}
                    </select>
                  </div>

                  {/* EMT/Staff deploy */}
                  <div>
                    <label style={{ fontSize: '0.65rem', color: '#64748B', textTransform: 'uppercase', letterSpacing: '1px', fontWeight: 700, display: 'block', marginBottom: 6 }}>Assign Staff (EMT/Doctor)</label>
                    <select value={formStaffId} onChange={e => setFormStaffId(e.target.value)}
                      style={{ width: '100%', padding: '10px 14px', background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 10, color: '#fff', fontSize: '0.85rem', outline: 'none' }}>
                      <option value="" style={{ background: '#0D1526' }}>-- Select Staff Member --</option>
                      <optgroup label="Emergency Medical Techs" style={{ background: '#0D1526' }}>
                        {emtOptions.map(emt => (
                          <option key={emt.id} value={emt.id}>{emt.name}</option>
                        ))}
                      </optgroup>
                      <optgroup label="MD Physicians" style={{ background: '#0D1526' }}>
                        {doctorOptions.map(doc => (
                          <option key={doc.id} value={doc.id}>{doc.name}</option>
                        ))}
                      </optgroup>
                    </select>
                  </div>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  {/* Start Date */}
                  <div>
                    <label style={{ fontSize: '0.65rem', color: '#64748B', textTransform: 'uppercase', letterSpacing: '1px', fontWeight: 700, display: 'block', marginBottom: 6 }}>Start Date</label>
                    <input type="date" value={formStartDate} onChange={e => setFormStartDate(e.target.value)}
                      style={{ width: '100%', padding: '9px 12px', background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 10, color: '#fff', fontSize: '0.85rem', outline: 'none', boxSizing: 'border-box' }} />
                  </div>

                  {/* End Date */}
                  <div>
                    <label style={{ fontSize: '0.65rem', color: '#64748B', textTransform: 'uppercase', letterSpacing: '1px', fontWeight: 700, display: 'block', marginBottom: 6 }}>End Date</label>
                    <input type="date" value={formEndDate} onChange={e => setFormEndDate(e.target.value)}
                      style={{ width: '100%', padding: '9px 12px', background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 10, color: '#fff', fontSize: '0.85rem', outline: 'none', boxSizing: 'border-box' }} />
                  </div>
                </div>

                {/* Notes */}
                <div>
                  <label style={{ fontSize: '0.65rem', color: '#64748B', textTransform: 'uppercase', letterSpacing: '1px', fontWeight: 700, display: 'block', marginBottom: 6 }}>Roster Notes</label>
                  <input type="text" value={formNotes} onChange={e => setFormNotes(e.target.value)} placeholder="e.g. Active dispatch on V-001 ALS"
                    style={{ width: '100%', padding: '10px 14px', background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 10, color: '#fff', fontSize: '0.85rem', outline: 'none', boxSizing: 'border-box' }} />
                </div>

                {rosterErr && (
                  <div style={{ background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)', padding: '10px 12px', borderRadius: 10, color: '#EF4444', fontSize: '0.75rem', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <AlertCircle size={14} /> {rosterErr}
                  </div>
                )}

                {rosterSuccess && (
                  <div style={{ background: 'rgba(16,185,129,0.08)', border: '1px solid rgba(16,185,129,0.2)', padding: '10px 12px', borderRadius: 10, color: '#10B981', fontSize: '0.75rem', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Check size={14} /> {rosterSuccess}
                  </div>
                )}

                <button onClick={handleCreateAssignment} disabled={submittingRoster}
                  style={{ width: '100%', padding: '12px', background: 'linear-gradient(135deg,#06B6D4,#3B82F6)', border: 'none', borderRadius: 12, color: '#fff', fontWeight: 800, fontSize: '0.88rem', cursor: submittingRoster ? 'not-allowed' : 'pointer', marginTop: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
                  {submittingRoster ? <Loader2 size={16} className="spin" /> : 'FINALIZE ROSTER'}
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <style>{`@keyframes spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}} .spin{animation:spin 1s linear infinite}`}</style>
    </div>
  );
};
