import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { incidentsApi } from '../api/incidents';
import type { Patient, Incident } from '../api/types';

import { 
  Plus, 
  Search, 
  Filter, 
  Download, 
  MapPin, 
  Clock, 
  User, 
  Activity, 
  ChevronRight, 
  PhoneCall,
  Truck,
  Hospital,
  UserCheck,
  Navigation,
  X,
  AlertCircle,
  ShieldAlert,
  CheckCircle2,
  Minus,
  Info,
  Heart,
  ChevronLeft,
  Zap,
  LayoutDashboard,
  Signal
} from 'lucide-react';
import { Card } from '../components/Common';
import { motion, AnimatePresence } from 'framer-motion';

// --- Types & Constants ---
type TriageCategory = 'RED' | 'ORANGE' | 'GREEN' | 'WHITE' | 'BLACK';

interface BookingRecord {
  id: string;
  caller: string;
  phone: string;
  triage: TriageCategory;
  pickupLocation: string;
  patients: number;
  symptoms: string[];
  status: 'PENDING' | 'DISPATCHED' | 'EN_ROUTE' | 'ON_SITE' | 'COMPLETED' | 'CANCELLED';
  timestamp: string;
  eta?: string;
  receivedBy: string;
  fleetOperator: string;
  assignedVehicle: string;
  destinationHospital: string;
}

const CATEGORIES: { type: TriageCategory; label: string; description: string; color: string; icon: any }[] = [
  { type: 'RED', label: 'Life Threatening', description: 'Cardiac arrest, severe injury, unconscious', color: '#ff4d4d', icon: ShieldAlert },
  { type: 'ORANGE', label: 'Urgent', description: 'Fractures, moderate injuries, severe pain', color: '#ffa500', icon: AlertCircle },
  { type: 'GREEN', label: 'Less Urgent', description: 'Minor injuries, non-critical', color: '#00e676', icon: Activity },
  { type: 'WHITE', label: 'Non-Emergency', description: 'Scheduled transport, routine transfer', color: 'var(--text-secondary)', icon: User },
  { type: 'BLACK', label: 'Dead', description: 'Deceased person, mortuary transport', color: '#9e9e9e', icon: Clock }
];

const COMMON_SYMPTOMS = ['Fainting', 'Bleeding', 'Choking', 'Fits', 'Burns', 'Breathing Difficulty', 'Chest Pain', 'Head Injury' ];

const SEVERITY_LEVELS = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
const INCIDENT_CATEGORIES = ['MEDICAL', 'FIRE', 'ACCIDENT', 'TRAUMA', 'CARDIAC'];
const GENDERS = ['Male', 'Female', 'Other'];


const MOCK_DATA: BookingRecord[] = [
  {
    id: 'BK-1001',
    caller: 'John Doe',
    phone: '+91 98765 43210',
    triage: 'RED',
    pickupLocation: '221B Baker Street, London',
    patients: 1,
    symptoms: ['Chest Pain', 'Breathing Difficulty'],
    status: 'EN_ROUTE',
    timestamp: '2026-04-18 08:45',
    eta: '4 mins',
    receivedBy: 'Admin Sarah',
    fleetOperator: 'CureSelect North',
    assignedVehicle: 'AMB-702 (Paramedic Rajesh)',
    destinationHospital: 'City General Hospital'
  },
  {
    id: 'BK-1002',
    caller: 'Sarah Williams',
    phone: '+91 98888 77777',
    triage: 'ORANGE',
    pickupLocation: 'Central Square Mall, Floor 2',
    patients: 2,
    symptoms: ['Bleeding', 'Fracture'],
    status: 'DISPATCHED',
    timestamp: '2026-04-18 09:02',
    eta: '8 mins',
    receivedBy: 'Admin Mike',
    fleetOperator: 'Apollo Fleet',
    assignedVehicle: 'V-881 (Nurse Anita)',
    destinationHospital: 'Apollo Speciality Hub'
  },
  {
    id: 'BK-1003',
    caller: 'Unknown (Highway)',
    phone: '+91 95555 44444',
    triage: 'RED',
    pickupLocation: 'NH-45, Milestone 12',
    patients: 3,
    symptoms: ['Head Injury', 'Unconscious'],
    status: 'PENDING',
    timestamp: '2026-04-18 09:12',
    receivedBy: 'System Auto',
    fleetOperator: 'Govt Dispatch',
    assignedVehicle: 'PENDING',
    destinationHospital: 'Trauma Hub'
  }
];

const TRIAGE_COLORS = {
  RED: { bg: 'rgba(255, 77, 77, 0.15)', text: '#ff4d4d', border: 'rgba(255, 77, 77, 0.3)', glow: '0 0 10px rgba(255, 77, 77, 0.1)' },
  ORANGE: { bg: 'rgba(255, 165, 0, 0.15)', text: '#ffa500', border: 'rgba(255, 165, 0, 0.3)', glow: '0 0 10px rgba(255, 165, 0, 0.1)' },
  GREEN: { bg: 'rgba(0, 230, 118, 0.15)', text: '#00e676', border: 'rgba(0, 230, 118, 0.3)', glow: '0 0 10px rgba(0, 230, 118, 0.1)' },
  WHITE: { bg: 'rgba(0, 0, 0, 0.02)', text: 'var(--text-primary)', border: 'var(--card-border)', glow: 'none' },
  BLACK: { bg: 'rgba(0, 0, 0, 0.05)', text: '#9e9e9e', border: 'var(--card-border)', glow: 'none' }
};

const STATUS_COLORS = {
  PENDING: '#ffa500',
  DISPATCHED: '#3B82F6',
  EN_ROUTE: '#3B82F6',
  ON_SITE: '#00e676',
  COMPLETED: '#9e9e9e',
  CANCELLED: '#ff4d4d'
};

export const CallerPortal: React.FC = () => {
  const navigate = useNavigate();
  const [searchTerm, setSearchTerm] = useState('');
  const [isBookingModalOpen, setIsBookingModalOpen] = useState(false);
  const [bookingStep, setBookingStep] = useState(1);
  const [isLoading, setIsLoading] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  const [newBooking, setNewBooking] = useState<Partial<Incident>>({
    category: 'MEDICAL',
    triage_level: 'RED',
    severity: 'CRITICAL',
    organisationId: '3fa85f64-5717-4562-b3fc-2c963f66afa6',
    gps_lat: 12.971598,
    gps_lon: 77.594566,
    address: '',
    guest_name: '',
    guest_phone: '',
    patients: [
      {
        name: '',
        age: 0,
        gender: 'Male',
        triage_level: 'RED',
        symptoms: []
      }
    ],
    notes: ''
  });

  // Persistence logic
  useEffect(() => {
    const savedBooking = localStorage.getItem('active_incident_booking');
    const savedStep = localStorage.getItem('active_incident_step');
    const savedModalState = localStorage.getItem('active_incident_modal_open');

    if (savedBooking) setNewBooking(JSON.parse(savedBooking));
    if (savedStep) setBookingStep(parseInt(savedStep));
    if (savedModalState === 'true') setIsBookingModalOpen(true);
  }, []);

  useEffect(() => {
    if (isBookingModalOpen) {
      localStorage.setItem('active_incident_booking', JSON.stringify(newBooking));
      localStorage.setItem('active_incident_step', bookingStep.toString());
      localStorage.setItem('active_incident_modal_open', 'true');
    } else {
      localStorage.removeItem('active_incident_booking');
      localStorage.removeItem('active_incident_step');
      localStorage.removeItem('active_incident_modal_open');
    }
  }, [newBooking, bookingStep, isBookingModalOpen]);

  // Warning before leave
  useEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (isBookingModalOpen) {
        e.preventDefault();
        e.returnValue = '';
      }
    };
    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, [isBookingModalOpen]);


  const handleNext = () => setBookingStep(s => s + 1);
  const handleBack = () => setBookingStep(s => s - 1);

  const addPatient = () => {
    setNewBooking(prev => ({
      ...prev,
      patients: [
        ...(prev.patients || []),
        { name: '', age: 0, gender: 'Male', triage_level: 'RED', symptoms: [] }
      ]
    }));
  };

  const removePatient = (index: number) => {
    setNewBooking(prev => ({
      ...prev,
      patients: (prev.patients || []).filter((_, i) => i !== index)
    }));
  };

  const updatePatient = (index: number, updates: Partial<Patient>) => {
    setNewBooking(prev => {
      const updatedPatients = [...(prev.patients || [])];
      updatedPatients[index] = { ...updatedPatients[index], ...updates };
      return { ...prev, patients: updatedPatients };
    });
  };

  const toggleSymptom = (patientIndex: number, symptomName: string) => {
    setNewBooking(prev => {
      const updatedPatients = [...(prev.patients || [])];
      const patient = updatedPatients[patientIndex];
      const exists = patient.symptoms.find(s => s.name === symptomName);
      
      if (exists) {
        patient.symptoms = patient.symptoms.filter(s => s.name !== symptomName);
      } else {
        patient.symptoms = [...patient.symptoms, { name: symptomName, duration_minutes: 10 }];
      }
      
      updatedPatients[patientIndex] = patient;
      return { ...prev, patients: updatedPatients };
    });
  };

  const handleAuthorizeDispatch = async () => {
    setIsLoading(true);
    const token = localStorage.getItem('teleems_token') || '';
    try {
      const response = await incidentsApi.createIncident(newBooking, token);
      if (response && (response.status === 200 || response.status === 201)) {
        setSuccessMessage("MISSION AUTHORIZED: DISPATCH SEQUENCE INITIATED");
        localStorage.removeItem('active_incident_booking');
        localStorage.removeItem('active_incident_step');
        localStorage.removeItem('active_incident_modal_open');
        setTimeout(() => {
          setIsBookingModalOpen(false);
          setBookingStep(1);
          setSuccessMessage(null);
        }, 2000);
      }

    } catch (error) {
      console.error("Dispatch failed:", error);
    } finally {
      setIsLoading(false);
    }
  };


  const containerVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0, transition: { duration: 0.5, staggerChildren: 0.1 } }
  };

  const itemVariants = {
    hidden: { opacity: 0, x: -10 },
    visible: { opacity: 1, x: 0 }
  };

  const renderBookingStep = () => {
    if (successMessage) {
      return (
        <motion.div 
          initial={{ opacity: 0, scale: 0.9 }} 
          animate={{ opacity: 1, scale: 1 }}
          style={{ textAlign: 'center', padding: '40px 0' }}
        >
          <div style={{ width: '80px', height: '80px', background: 'rgba(0, 230, 118, 0.1)', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 24px' }}>
            <CheckCircle2 size={48} color="#00e676" />
          </div>
          <h3 style={{ fontSize: '1.5rem', fontWeight: 900, color: '#00e676', marginBottom: '12px' }}>{successMessage}</h3>
          <p style={{ color: 'var(--text-secondary)' }}>Transmitting coordinates to nearest tactical units...</p>
        </motion.div>
      );
    }

    switch (bookingStep) {
      case 1:
        return (
          <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }}>
            <h3 style={{ fontSize: '1.4rem', fontWeight: 800, marginBottom: '24px', letterSpacing: '-0.5px' }}>Severity Assessment</h3>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '14px', marginBottom: '24px' }}>
              {CATEGORIES.map(cat => (
                <motion.button 
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                  key={cat.type} 
                  onClick={() => { setNewBooking({...newBooking, triage_level: cat.type}); }}
                  className="glass"
                  style={{ 
                    padding: '20px', borderRadius: '16px', textAlign: 'left', cursor: 'pointer',
                    border: `1px solid ${newBooking.triage_level === cat.type ? cat.color : 'var(--card-border)'}`,
                    background: newBooking.triage_level === cat.type ? `${cat.color}15` : 'rgba(0,0,0,0.02)',
                    display: 'flex', alignItems: 'center', gap: '18px',
                    transition: 'all 0.3s ease'
                  }}
                >
                  <div style={{ 
                    padding: '12px', background: `${cat.color}20`, borderRadius: '12px', color: cat.color,
                    boxShadow: newBooking.triage_level === cat.type ? `0 0 15px ${cat.color}40` : 'none'
                  }}>
                    <cat.icon size={28} />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 800, color: cat.color, fontSize: '1.1rem' }}>{cat.label}</div>
                    <div style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', marginTop: '2px' }}>{cat.description}</div>
                  </div>
                  {newBooking.triage_level === cat.type && <CheckCircle2 size={20} color={cat.color} />}
                </motion.button>
              ))}
            </div>
            
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
              <div>
                 <label style={{ fontSize: '0.7rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'block', marginBottom: '8px' }}>Category</label>
                 <select 
                    value={newBooking.category} 
                    onChange={e => setNewBooking({...newBooking, category: e.target.value})}
                    className="glass"
                    style={{ width: '100%', padding: '12px', borderRadius: '10px', border: '1px solid var(--card-border)', background: 'transparent', color: 'var(--text-primary)', fontWeight: 700 }}
                 >
                    {INCIDENT_CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
                 </select>
              </div>
              <div>
                 <label style={{ fontSize: '0.7rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'block', marginBottom: '8px' }}>Severity</label>
                 <select 
                    value={newBooking.severity} 
                    onChange={e => setNewBooking({...newBooking, severity: e.target.value})}
                    className="glass"
                    style={{ width: '100%', padding: '12px', borderRadius: '10px', border: '1px solid var(--card-border)', background: 'transparent', color: 'var(--text-primary)', fontWeight: 700 }}
                 >
                    {SEVERITY_LEVELS.map(s => <option key={s} value={s}>{s}</option>)}
                 </select>
              </div>
            </div>

            <button onClick={handleNext} className="hover-glow" style={{ width: '100%', padding: '18px', borderRadius: '16px', background: '#3B82F6', border: 'none', color: '#fff', fontWeight: 900, cursor: 'pointer', fontSize: '1rem', marginTop: '24px' }}>NEXT: CALLER INFO</button>
          </motion.div>
        );
      case 2:
        return (
          <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }}>
            <h3 style={{ fontSize: '1.4rem', fontWeight: 800, marginBottom: '24px' }}>Caller & Location</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div style={{ position: 'relative' }}>
                  <User size={18} style={{ position: 'absolute', left: '16px', top: '50%', transform: 'translateY(-50%)', opacity: 0.4 }} />
                  <input 
                    placeholder="Guest Name" 
                    value={newBooking.guest_name || ''}
                    onChange={e => setNewBooking({...newBooking, guest_name: e.target.value})}
                    className="glass" 
                    style={{ width: '100%', padding: '16px 16px 16px 48px', background: 'rgba(0,0,0,0.01)', border: '1px solid var(--card-border)', borderRadius: '12px', color: 'var(--text-primary)', fontSize: '0.9rem' }} 
                  />
                </div>
                <div style={{ position: 'relative' }}>
                  <PhoneCall size={18} style={{ position: 'absolute', left: '16px', top: '50%', transform: 'translateY(-50%)', opacity: 0.4 }} />
                  <input 
                    placeholder="Guest Phone" 
                    value={newBooking.guest_phone || ''}
                    onChange={e => setNewBooking({...newBooking, guest_phone: e.target.value})}
                    className="glass" 
                    style={{ width: '100%', padding: '16px 16px 16px 48px', background: 'rgba(0,0,0,0.01)', border: '1px solid var(--card-border)', borderRadius: '12px', color: 'var(--text-primary)', fontSize: '0.9rem' }} 
                  />
                </div>
              </div>
              
              <div style={{ position: 'relative' }}>
                <MapPin size={18} style={{ position: 'absolute', left: '16px', top: '18px', opacity: 0.4 }} />
                <textarea 
                  placeholder="Full Pickup Address" 
                  value={newBooking.address || ''}
                  onChange={e => setNewBooking({...newBooking, address: e.target.value})}
                  className="glass" 
                  style={{ width: '100%', padding: '16px 16px 16px 48px', background: 'rgba(0,0,0,0.01)', border: '1px solid var(--card-border)', borderRadius: '12px', color: 'var(--text-primary)', fontSize: '0.9rem', minHeight: '80px', resize: 'none' }} 
                />
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div style={{ position: 'relative' }}>
                  <Navigation size={16} style={{ position: 'absolute', left: '16px', top: '50%', transform: 'translateY(-50%)', opacity: 0.4 }} />
                  <input 
                    type="number"
                    placeholder="Lat" 
                    value={newBooking.gps_lat}
                    onChange={e => setNewBooking({...newBooking, gps_lat: parseFloat(e.target.value)})}
                    className="glass" 
                    style={{ width: '100%', padding: '12px 12px 12px 40px', background: 'rgba(0,0,0,0.01)', border: '1px solid var(--card-border)', borderRadius: '10px', color: 'var(--text-primary)', fontSize: '0.8rem' }} 
                  />
                </div>
                <div style={{ position: 'relative' }}>
                  <Navigation size={16} style={{ position: 'absolute', left: '16px', top: '50%', transform: 'translateY(-50%)', opacity: 0.4 }} />
                  <input 
                    type="number"
                    placeholder="Lon" 
                    value={newBooking.gps_lon}
                    onChange={e => setNewBooking({...newBooking, gps_lon: parseFloat(e.target.value)})}
                    className="glass" 
                    style={{ width: '100%', padding: '12px 12px 12px 40px', background: 'rgba(0,0,0,0.01)', border: '1px solid var(--card-border)', borderRadius: '10px', color: 'var(--text-primary)', fontSize: '0.8rem' }} 
                  />
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: '12px', marginTop: '32px' }}>
              <button onClick={handleBack} className="glass" style={{ flex: 1, padding: '16px', borderRadius: '12px', border: '1px solid var(--card-border)', color: 'var(--text-secondary)', cursor: 'pointer', fontWeight: 700 }}>BACK</button>
              <button onClick={handleNext} className="hover-glow" style={{ flex: 2, padding: '16px', borderRadius: '12px', background: '#3B82F6', border: 'none', color: '#fff', fontWeight: 800, cursor: 'pointer', fontSize: '1rem' }}>PATIENT DETAILS</button>
            </div>
          </motion.div>
        );
      case 3:
        return (
          <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
              <h3 style={{ fontSize: '1.4rem', fontWeight: 800, margin: 0 }}>Patient Registry</h3>
              <button onClick={addPatient} style={{ background: 'rgba(59, 130, 246, 0.1)', border: '1px solid #3B82F6', color: '#3B82F6', padding: '6px 12px', borderRadius: '8px', cursor: 'pointer', fontSize: '0.8rem', fontWeight: 800, display: 'flex', alignItems: 'center', gap: '6px' }}>
                <Plus size={14} /> ADD PATIENT
              </button>
            </div>
            
            <div style={{ display: 'flex', flexDirection: 'column', gap: '20px', maxHeight: '400px', overflowY: 'auto', paddingRight: '4px' }} className="no-scrollbar">
              {newBooking.patients?.map((patient, idx) => (
                <div key={idx} className="glass" style={{ padding: '20px', borderRadius: '20px', border: '1px solid var(--card-border)', position: 'relative' }}>
                  <button onClick={() => removePatient(idx)} style={{ position: 'absolute', top: '10px', right: '10px', background: 'none', border: 'none', color: '#ff4d4d', cursor: 'pointer', opacity: 0.6 }}>
                    <X size={18} />
                  </button>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '16px' }}>
                    <div style={{ width: '24px', height: '24px', background: '#3B82F6', borderRadius: '50%', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '0.7rem', fontWeight: 900 }}>{idx + 1}</div>
                    <span style={{ fontWeight: 800, fontSize: '0.9rem' }}>Patient Assessment</span>
                  </div>
                  
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                      <label style={{ fontSize: '0.65rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Full Name</label>
                      <input 
                        placeholder="Patient Name" 
                        value={patient.name}
                        onChange={e => updatePatient(idx, { name: e.target.value })}
                        className="glass" 
                        style={{ padding: '10px', borderRadius: '8px', border: '1px solid var(--card-border)', background: 'rgba(0,0,0,0.01)', color: 'var(--text-primary)', fontSize: '0.85rem', width: '100%' }} 
                      />
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                      <label style={{ fontSize: '0.65rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Age</label>
                      <input 
                        type="number"
                        placeholder="Age" 
                        value={patient.age || ''}
                        onChange={e => updatePatient(idx, { age: parseInt(e.target.value) || 0 })}
                        className="glass" 
                        style={{ padding: '10px', borderRadius: '8px', border: '1px solid var(--card-border)', background: 'rgba(0,0,0,0.01)', color: 'var(--text-primary)', fontSize: '0.85rem', width: '100%' }} 
                      />
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                      <label style={{ fontSize: '0.65rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Gender</label>
                      <select 
                        value={patient.gender}
                        onChange={e => updatePatient(idx, { gender: e.target.value })}
                        className="glass" 
                        style={{ padding: '10px', borderRadius: '8px', border: '1px solid var(--card-border)', background: 'transparent', color: 'var(--text-primary)', fontSize: '0.85rem', width: '100%' }}
                      >
                        {GENDERS.map(g => <option key={g} value={g}>{g}</option>)}
                      </select>
                    </div>


                  <div style={{ marginBottom: '16px' }}>
                    <label style={{ fontSize: '0.65rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '8px', display: 'block' }}>Triage</label>
                    <div style={{ display: 'flex', gap: '6px' }}>
                      {CATEGORIES.map(cat => (
                        <button 
                          key={cat.type}
                          onClick={() => updatePatient(idx, { triage_level: cat.type })}
                          style={{ 
                            flex: 1, padding: '8px', borderRadius: '6px', fontSize: '0.65rem', fontWeight: 800, cursor: 'pointer',
                            background: patient.triage_level === cat.type ? `${cat.color}20` : 'rgba(0,0,0,0.02)',
                            border: `1px solid ${patient.triage_level === cat.type ? cat.color : 'var(--card-border)'}`,
                            color: patient.triage_level === cat.type ? cat.color : 'var(--text-secondary)'
                          }}
                        >
                          {cat.type}
                        </button>
                      ))}
                    </div>
                  </div>

                  <div>
                    <label style={{ fontSize: '0.65rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '8px', display: 'block' }}>Symptoms</label>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
                      {COMMON_SYMPTOMS.map(s => {
                        const isSelected = patient.symptoms.some(sym => sym.name === s);
                        return (
                          <div key={s} style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                            <button 
                              onClick={() => toggleSymptom(idx, s)}
                              style={{ 
                                padding: '6px 12px', borderRadius: '20px', fontSize: '0.7rem', fontWeight: 600, cursor: 'pointer',
                                background: isSelected ? 'rgba(59, 130, 246, 0.1)' : 'rgba(0,0,0,0.02)',
                                border: `1px solid ${isSelected ? '#3B82F6' : 'var(--card-border)'}`,
                                color: isSelected ? '#3B82F6' : 'var(--text-secondary)',
                                display: 'flex', alignItems: 'center', gap: '8px'
                              }}
                            >
                              {s}
                              {isSelected && (
                                <div style={{ display: 'flex', alignItems: 'center', gap: '4px', borderLeft: '1px solid rgba(59, 130, 246, 0.3)', paddingLeft: '8px' }}>
                                   <Clock size={12} />
                                   <input 
                                      type="number"
                                      value={patient.symptoms.find(sym => sym.name === s)?.duration_minutes || 10}
                                      onClick={e => e.stopPropagation()}
                                      onChange={e => {
                                        e.stopPropagation();
                                        const val = parseInt(e.target.value) || 0;
                                        updatePatient(idx, {
                                          symptoms: patient.symptoms.map(sym => sym.name === s ? { ...sym, duration_minutes: val } : sym)
                                        });
                                      }}
                                      style={{ width: '30px', background: 'transparent', border: 'none', color: '#3B82F6', fontSize: '0.7rem', fontWeight: 900, outline: 'none' }}
                                   />
                                   <span style={{ fontSize: '0.6rem', opacity: 0.7 }}>m</span>
                                </div>
                              )}
                            </button>
                          </div>

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

            <div style={{ display: 'flex', gap: '12px', marginTop: '32px' }}>
              <button onClick={handleBack} className="glass" style={{ flex: 1, padding: '16px', borderRadius: '12px', border: '1px solid var(--card-border)', color: 'var(--text-secondary)', cursor: 'pointer', fontWeight: 700 }}>BACK</button>
              <button onClick={handleNext} className="hover-glow" style={{ flex: 2, padding: '16px', borderRadius: '12px', background: '#3B82F6', border: 'none', color: '#fff', fontWeight: 800, cursor: 'pointer', fontSize: '1rem' }}>MISSION REVIEW</button>
            </div>
          </motion.div>
        );
      case 4:
        return (
          <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }}>
            <h3 style={{ fontSize: '1.4rem', fontWeight: 800, marginBottom: '24px' }}>Finalize Mission</h3>
            
            <div style={{ display: 'flex', flexDirection: 'column', gap: '16px', marginBottom: '24px' }}>
              <div className="glass" style={{ padding: '16px', borderRadius: '12px', background: 'rgba(59, 130, 246, 0.05)', border: '1px solid rgba(59, 130, 246, 0.1)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '12px' }}>
                  <Activity size={18} color="#3B82F6" />
                  <span style={{ fontWeight: 800, fontSize: '0.9rem' }}>Mission Summary</span>
                </div>
                <div style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                   <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Category:</span> <span style={{ fontWeight: 700, color: 'var(--text-primary)' }}>{newBooking.category}</span></div>
                   <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Severity:</span> <span style={{ fontWeight: 700, color: '#ff4d4d' }}>{newBooking.severity}</span></div>
                   <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Total Patients:</span> <span style={{ fontWeight: 700, color: 'var(--text-primary)' }}>{newBooking.patients?.length}</span></div>
                   <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Location:</span> <span style={{ fontWeight: 700, color: 'var(--text-primary)', maxWidth: '200px', textAlign: 'right', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{newBooking.address}</span></div>
                </div>
              </div>
              
              <div>
                <label style={{ fontSize: '0.7rem', fontWeight: 800, color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '8px', display: 'block' }}>Field Notes / Instructions</label>
                <textarea 
                  placeholder="Any additional info for responders..." 
                  value={newBooking.notes || ''}
                  onChange={e => setNewBooking({...newBooking, notes: e.target.value})}
                  className="glass" 
                  style={{ width: '100%', padding: '16px', background: 'rgba(0,0,0,0.01)', border: '1px solid var(--card-border)', borderRadius: '12px', color: 'var(--text-primary)', fontSize: '0.9rem', minHeight: '100px', resize: 'none' }} 
                />
              </div>
            </div>

            <div style={{ display: 'flex', gap: '12px', marginTop: '32px' }}>
              <button onClick={handleBack} className="glass" style={{ flex: 1, padding: '16px', borderRadius: '12px', border: '1px solid var(--card-border)', color: 'var(--text-secondary)', cursor: 'pointer', fontWeight: 700 }}>BACK</button>
              <button 
                onClick={handleAuthorizeDispatch} 
                disabled={isLoading}
                className="hover-glow pulse-glow" 
                style={{ 
                  flex: 2, padding: '16px', borderRadius: '12px', background: 'linear-gradient(135deg, #3B82F6, #1d4ed8)', border: 'none', color: '#fff', fontWeight: 900, cursor: 'pointer', fontSize: '1.1rem', letterSpacing: '0.5px',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '12px', opacity: isLoading ? 0.7 : 1
                }}
              >
                {isLoading ? <Clock size={20} className="spin" /> : <Zap size={20} />}
                {isLoading ? 'TRANSMITTING...' : 'AUTHORIZE DISPATCH'}
              </button>
            </div>
          </motion.div>
        );
      default: return null;
    }
  };


  return (
    <motion.div 
      initial="hidden" 
      animate="visible" 
      variants={containerVariants}
      className="page-container no-scrollbar" 
      style={{ display: 'flex', flexDirection: 'column', gap: '32px', position: 'relative' }}
    >
      {/* Decorative Orbs */}
      <div style={{ position: 'absolute', top: -50, right: -50, width: '300px', height: '300px', background: 'radial-gradient(circle, rgba(59, 130, 246, 0.1) 0%, transparent 70%)', pointerEvents: 'none', zIndex: 0 }} />
      <div style={{ position: 'absolute', bottom: 50, left: -50, width: '400px', height: '400px', background: 'radial-gradient(circle, rgba(255, 77, 77, 0.05) 0%, transparent 70%)', pointerEvents: 'none', zIndex: 0 }} />

      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', position: 'relative', zIndex: 1 }}>
        <motion.div variants={itemVariants}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
            <div style={{ padding: '6px', background: '#3B82F6', borderRadius: '6px' }}><Signal size={18} color="#fff" /></div>
            <span style={{ fontSize: '0.9rem', fontWeight: 800, color: '#3B82F6', letterSpacing: '2px', textTransform: 'uppercase' }}>Live Command</span>
          </div>
          <h2 style={{ fontSize: '3rem', fontWeight: 900, background: 'linear-gradient(135deg, var(--text-primary) 0%, #3B82F6 100%)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', letterSpacing: '-2px', lineHeight: 1 }}>
            Fleet Intelligence Nodes
          </h2>
          <p style={{ color: 'var(--text-secondary)', fontSize: '1rem', marginTop: '8px' }}>
            Real-time telemetry and resource orchestration for critical emergency services.
          </p>
        </motion.div>
        
        <motion.div variants={itemVariants} style={{ display: 'flex', gap: '14px' }}>
          <motion.button whileHover={{ scale: 1.05 }} className="glass" style={{ padding: '12px 24px', borderRadius: '14px', background: 'rgba(0,0,0,0.03)', border: '1px solid var(--card-border)', color: 'var(--text-primary)', display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer', fontWeight: 700 }}>
            <Download size={20} /> ARCHIVE
          </motion.button>
          <motion.button 
            onClick={() => setIsBookingModalOpen(true)}
            whileHover={{ scale: 1.05, boxShadow: '0 0 30px rgba(59, 130, 246, 0.5)' }}
            whileTap={{ scale: 0.95 }}
            className="emergency-btn pulse-glow" 
            style={{ 
              padding: '12px 32px', background: 'linear-gradient(135deg, #3B82F6 0%, #1d4ed8 100%)', 
              border: 'none', borderRadius: '14px', color: '#fff', fontWeight: 900, 
              display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer',
              fontSize: '1rem', letterSpacing: '0.5px'
            }}>
            <Plus size={24} strokeWidth={3} /> EMERGENCY MISSION
          </motion.button>
        </motion.div>
      </header>

      {/* Modern Stats Layer */}
      <motion.div variants={containerVariants} style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '24px', position: 'relative', zIndex: 1 }}>
        {[
          { label: 'Network Throughput', value: '142 Cases', icon: Activity, color: '#3B82F6', trend: '+12%' },
          { label: 'Pending Dispatch', value: '03 Critical', icon: ShieldAlert, color: '#ff4d4d', trend: 'P0 Priority' },
          { label: 'Active Coverage', value: '92.4%', icon: Navigation, color: '#00e676', trend: 'Optimal' },
          { label: 'Operator Status', value: '12 Units', icon: UserCheck, color: 'var(--text-primary)', trend: 'Online' }
        ].map((stat, i) => (
          <motion.div key={i} variants={itemVariants} whileHover={{ y: -5 }}>
            <Card style={{ padding: '24px', position: 'relative', overflow: 'hidden', borderLeft: `6px solid ${stat.color}` }}>
              <div style={{ position: 'absolute', right: '-10px', top: '-10px', opacity: 0.05 }}><stat.icon size={100} /></div>
              <div style={{ color: 'var(--text-secondary)', fontSize: '0.75rem', textTransform: 'uppercase', fontWeight: 900, letterSpacing: '1px' }}>{stat.label}</div>
              <div style={{ fontSize: '2rem', fontWeight: 900, marginTop: '12px', color: 'var(--text-primary)', letterSpacing: '-1px' }}>{stat.value}</div>
              <div style={{ marginTop: '12px', display: 'flex', alignItems: 'center', gap: '8px' }}>
                <div style={{ padding: '2px 8px', borderRadius: '10px', background: `${stat.color}15`, color: stat.color, fontSize: '0.7rem', fontWeight: 900 }}>{stat.trend}</div>
                <div style={{ flex: 1, height: '2px', background: 'rgba(0,0,0,0.05)', borderRadius: '1px' }}>
                   <div style={{ width: '70%', height: '100%', background: stat.color, borderRadius: '1px', boxShadow: `0 0 10px ${stat.color}` }} />
                </div>
              </div>
            </Card>
          </motion.div>
        ))}
      </motion.div>

      {/* Refined Command Grid */}
      <motion.div variants={itemVariants} style={{ position: 'relative', zIndex: 1 }}>
        <Card style={{ padding: '0', overflow: 'hidden', borderRadius: '24px', border: '1px solid var(--card-border)', background: 'var(--card-bg)' }}>
          <div style={{ padding: '24px', borderBottom: '1px solid rgba(0,0,0,0.02)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
             <h3 style={{ display: 'flex', alignItems: 'center', gap: '12px', margin: 0, fontSize: '1.2rem', fontWeight: 800 }}>
                <LayoutDashboard size={22} color="#3B82F6" /> 
                System Access Registry
             </h3>
             <div className="glass" style={{ padding: '8px 16px', borderRadius: '12px', display: 'flex', alignItems: 'center', gap: '12px', border: '1px solid var(--card-border)' }}>
                <Search size={18} color="var(--text-secondary)" />
                <input placeholder="Filter missions..." style={{ background: 'transparent', border: 'none', color: 'var(--text-primary)', outline: 'none', fontSize: '0.9rem' }} />
             </div>
          </div>
          
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', minWidth: '1100px' }}>
              <thead>
                 <tr style={{ background: 'rgba(0,0,0,0.01)' }}>
                  <th style={{ padding: '20px 24px', fontSize: '0.75rem', color: 'var(--text-secondary)', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '1px' }}>ID & Mission Log</th>
                  <th style={{ padding: '20px 24px', fontSize: '0.75rem', color: 'var(--text-secondary)', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '1px' }}>Caller Registry</th>
                  <th style={{ padding: '20px 24px', fontSize: '0.75rem', color: 'var(--text-secondary)', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '1px' }}>Operational Node</th>
                  <th style={{ padding: '20px 24px', fontSize: '0.75rem', color: 'var(--text-secondary)', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '1px' }}>Tactical Rescue</th>
                  <th style={{ padding: '20px 24px', fontSize: '0.75rem', color: 'var(--text-secondary)', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '1px' }}>Logistics pathway</th>
                  <th style={{ padding: '20px 24px', textAlign: 'right' }}></th>
                </tr>
              </thead>
              <tbody>
                {MOCK_DATA.map((row) => (
                  <motion.tr 
                    key={row.id} 
                    whileHover={{ background: 'rgba(59, 130, 246, 0.02)' }}
                    style={{ borderBottom: '1px solid rgba(0,0,0,0.02)', cursor: 'default', transition: 'background 0.3s' }}
                  >
                    <td style={{ padding: '20px 24px' }}>
                      <div className="mono" style={{ fontWeight: 900, fontSize: '0.9rem', color: '#3B82F6' }}>{row.id}</div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginTop: '6px', opacity: 0.4 }}>
                        <Clock size={12} />
                        <span style={{ fontSize: '0.7rem' }}>{row.timestamp}</span>
                      </div>
                    </td>
                    <td style={{ padding: '20px 24px' }}>
                      <div style={{ fontWeight: 800, fontSize: '1rem' }}>{row.caller}</div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '8px' }}>
                        <span style={{ 
                           fontSize: '0.6rem', padding: '3px 8px', borderRadius: '6px', fontWeight: 900,
                           background: TRIAGE_COLORS[row.triage].bg, color: TRIAGE_COLORS[row.triage].text, border: `1px solid ${TRIAGE_COLORS[row.triage].border}`,
                           boxShadow: TRIAGE_COLORS[row.triage].glow
                         }}>{row.triage}</span>
                        <div style={{ width: '4px', height: '4px', borderRadius: '50%', background: 'rgba(0,0,0,0.1)' }} />
                        <span style={{ fontSize: '0.8rem', fontWeight: 700, color: STATUS_COLORS[row.status] }}>{row.status.replace('_', ' ')}</span>
                      </div>
                    </td>
                    <td style={{ padding: '20px 24px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                        <div style={{ width: '40px', height: '40px', background: 'rgba(59, 130, 246, 0.1)', borderRadius: '10px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                           <UserCheck size={20} color="#3B82F6" />
                        </div>
                        <div>
                           <div style={{ fontSize: '0.9rem', fontWeight: 800 }}>{row.receivedBy}</div>
                           <div style={{ fontSize: '0.7rem', color: 'var(--text-secondary)', textTransform: 'uppercase', marginTop: '2px' }}>{row.fleetOperator}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ padding: '20px 24px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                         <div style={{ width: '40px', height: '40px', background: 'rgba(0, 230, 118, 0.1)', borderRadius: '10px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                            <Truck size={20} color="#00e676" />
                         </div>
                         <div>
                            <div style={{ fontSize: '0.95rem', fontWeight: 800 }}>{row.assignedVehicle}</div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginTop: '4px' }}>
                               <div className="pulse" style={{ width: '6px', height: '6px', borderRadius: '50%', background: '#00e676' }} />
                               <span style={{ fontSize: '0.7rem', color: '#00e676', fontWeight: 700 }}>{row.eta ? `+ ${row.eta} ETA` : 'Active'}</span>
                            </div>
                         </div>
                      </div>
                    </td>
                    <td style={{ padding: '20px 24px' }}>
                       <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', padding: '10px', background: 'rgba(0,0,0,0.01)', borderRadius: '12px', border: '1px solid var(--card-border)' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                             <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#ff4d4d', boxShadow: '0 0 8px #ff4d4d' }} />
                             <span style={{ fontSize: '0.8rem', fontWeight: 600, color: 'var(--text-secondary)', maxWidth: '160px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.pickupLocation}</span>
                          </div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                             <Hospital size={16} color="#3B82F6" />
                             <span style={{ fontSize: '0.85rem', fontWeight: 800, color: 'var(--text-primary)', whiteSpace: 'nowrap' }}>{row.destinationHospital}</span>
                          </div>
                       </div>
                    </td>
                    <td style={{ padding: '20px 24px', textAlign: 'right' }}>
                       <motion.button whileHover={{ x: 5 }} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#3B82F6' }}>
                          <ChevronRight size={24} />
                       </motion.button>
                    </td>
                  </motion.tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      </motion.div>

      {/* Modal - Re-designed for Attraction */}
      <AnimatePresence>
        {isBookingModalOpen && (
          <div className="modal-overlay" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(255,255,255,0.85)', backdropFilter: 'blur(15px)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>
            <motion.div 
              initial={{ opacity: 0, scale: 0.9, y: 30 }} 
              animate={{ opacity: 1, scale: 1, y: 0 }} 
              exit={{ opacity: 0, scale: 0.9, y: 30 }}
              className="glass" 
              style={{ 
                width: '100%', maxWidth: '540px', background: 'var(--card-bg)', borderRadius: '32px', padding: '40px', border: '1px solid #3B82F6', 
                boxShadow: '0 0 100px rgba(59, 130, 246, 0.05)', position: 'relative', overflowY: 'auto', maxHeight: '90vh'
              }}

            >
              {/* Decorative Modal Background */}
              <div style={{ position: 'absolute', top: -100, left: -100, width: '300px', height: '300px', background: 'radial-gradient(circle, rgba(59, 130, 246, 0.05) 0%, transparent 70%)', pointerEvents: 'none' }} />

              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '40px', position: 'relative', zIndex: 1 }}>
                 <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                    <div style={{ width: '48px', height: '48px', borderRadius: '16px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                       <Zap size={24} color="#3B82F6" />
                    </div>
                    <div>
                       <h2 style={{ fontSize: '1.6rem', fontWeight: 900, margin: 0, letterSpacing: '-0.5px' }}>Mission Config</h2>
                       <div style={{ display: 'flex', gap: '6px', marginTop: '4px' }}>
                          {[1, 2, 3, 4].map(i => <div key={i} style={{ width: '20px', height: '3px', borderRadius: '2px', background: i <= bookingStep ? '#3B82F6' : 'rgba(0,0,0,0.1)' }} />)}
                       </div>
                    </div>
                 </div>
                 <motion.button whileHover={{ rotate: 90 }} onClick={() => { setIsBookingModalOpen(false); setBookingStep(1); }} style={{ background: 'rgba(0,0,0,0.03)', border: 'none', borderRadius: '50%', padding: '10px', cursor: 'pointer', color: 'var(--text-secondary)' }}>
                   <X size={24} />
                 </motion.button>
              </div>

              <div style={{ position: 'relative', zIndex: 1 }}>
                {renderBookingStep()}
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      <style>{`
        .pulse-glow {
          animation: pulseGlow 3s infinite;
        }
        @keyframes pulseGlow {
          0% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4); }
          70% { box-shadow: 0 0 0 15px rgba(59, 130, 246, 0); }
          100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); }
        }
        .pulse {
          animation: pulsePoint 2s infinite;
        }
        @keyframes pulsePoint {
          0% { transform: scale(1); opacity: 1; }
          50% { transform: scale(1.5); opacity: 0.5; }
          100% { transform: scale(1); opacity: 1; }
        }
        .page-container::-webkit-scrollbar { display: none; }
      `}</style>
    </motion.div>
  );
};
