import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { 
  Activity, 
  Truck, 
  Users, 
  TrendingUp, 
  Calendar, 
  Clock, 
  AlertCircle, 
  Loader2, 
  RefreshCw,
  Award,
  Shield,
  MapPin,
  Car
} from 'lucide-react';
import { 
  ResponsiveContainer, 
  PieChart, 
  Pie, 
  Cell, 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  Legend,
  AreaChart,
  Area
} from 'recharts';
import { motion } from 'framer-motion';
import { fleetApi } from '../../api/fleet';
import { Pagination } from '../../components/Pagination';

interface APIVehicle {
  id: string;
  registration_number: string;
  chassis_number?: string | null;
  brand?: string;
  model?: string;
  vehicle_type: string;
  status?: string;
  ownership_type?: string;
  gps_lat?: string | number;
  gps_lon?: string | number;
  activeShift?: any;
  activeRoster?: any;
  createdAt?: string;
}

export const FleetAnalytics: React.FC = () => {
  const [vehicles, setVehicles] = useState<APIVehicle[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [timeRange, setTimeRange] = useState<'7D' | '30D' | 'ALL'>('ALL');
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(5);

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

  const fetchVehiclesData = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const res = await fleetApi.getVehicles(token);
      let list: APIVehicle[] = [];
      if (res?.data?.data && Array.isArray(res.data.data)) list = res.data.data;
      else if (res?.data && Array.isArray(res.data)) list = res.data;
      else if (Array.isArray(res)) list = res;
      setVehicles(list);
    } catch (err: any) {
      console.error('Failed to fetch vehicles for analytics:', err);
      setError('Failed to load fleet analytics data. Please try again.');
    } finally {
      setLoading(false);
    }
  }, [token]);

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

  // --- DERIVED ANALYTICS METRICS ---
  const stats = useMemo(() => {
    const total = vehicles.length;
    const available = vehicles.filter(v => v.status === 'AVAILABLE').length;
    const busy = vehicles.filter(v => v.status === 'BUSY').length;
    const offline = vehicles.filter(v => v.status === 'OFFLINE' || (!v.status)).length;
    const withActiveShift = vehicles.filter(v => v.activeShift !== null).length;
    const withActiveRoster = vehicles.filter(v => v.activeRoster !== null).length;
    const hasGps = vehicles.filter(v => v.gps_lat && parseFloat(v.gps_lat as string) !== 0).length;

    const utilizationRate = total > 0 ? Math.round(((busy + withActiveShift) / total) * 100) : 0;

    return {
      total,
      available,
      busy,
      offline,
      withActiveShift,
      withActiveRoster,
      hasGps,
      utilizationRate
    };
  }, [vehicles]);

  // Chart 1: Status Distribution
  const statusChartData = useMemo(() => {
    const statuses: Record<string, { count: number; color: string }> = {
      AVAILABLE: { count: 0, color: '#10B981' }, // Emerald
      BUSY: { count: 0, color: '#F59E0B' },      // Amber
      OFFLINE: { count: 0, color: '#475569' },   // Slate
      MAINTENANCE: { count: 0, color: '#EF4444' } // Red
    };

    vehicles.forEach(v => {
      const status = (v.status || 'OFFLINE').toUpperCase();
      if (statuses[status]) {
        statuses[status].count += 1;
      } else {
        statuses['OFFLINE'].count += 1;
      }
    });

    return Object.entries(statuses).map(([name, info]) => ({
      name,
      value: info.count,
      color: info.color
    })).filter(d => d.value > 0);
  }, [vehicles]);

  // Chart 2: Vehicle Type Breakdown
  const typeChartData = useMemo(() => {
    const types: Record<string, number> = {};
    vehicles.forEach(v => {
      const type = v.vehicle_type || 'Unknown';
      types[type] = (types[type] || 0) + 1;
    });

    const colors = ['#06B6D4', '#3B82F6', '#8B5CF6', '#EC4899', '#F43F5E'];
    return Object.entries(types).map(([name, value], idx) => ({
      name,
      value,
      color: colors[idx % colors.length]
    }));
  }, [vehicles]);

  // Chart 3: Shift / Roster Deployment Metrics
  const deploymentChartData = useMemo(() => {
    let activeShiftCount = 0;
    let scheduledRosterCount = 0;
    let unassignedCount = 0;

    vehicles.forEach(v => {
      if (v.activeShift) {
        activeShiftCount++;
      } else if (v.activeRoster) {
        scheduledRosterCount++;
      } else {
        unassignedCount++;
      }
    });

    return [
      { name: 'Active Shift (On Duty)', value: activeShiftCount, color: '#10B981' },
      { name: 'Scheduled Roster (Planned)', value: scheduledRosterCount, color: '#8B5CF6' },
      { name: 'Unassigned Units', value: unassignedCount, color: '#F59E0B' }
    ];
  }, [vehicles]);

  // Chart 4: Brand Representation
  const brandChartData = useMemo(() => {
    const brands: Record<string, number> = {};
    vehicles.forEach(v => {
      const brand = v.brand || 'Unspecified';
      brands[brand] = (brands[brand] || 0) + 1;
    });

    const colors = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'];
    return Object.entries(brands).map(([name, value], idx) => ({
      name,
      count: value,
      color: colors[idx % colors.length]
    }));
  }, [vehicles]);

  // Chart 5: Mock Fleet Mileage / Performance (Time Series)
  const performanceTrendData = useMemo(() => {
    return [
      { name: '06:00', trips: 2, responseTime: 8, efficiency: 94 },
      { name: '08:00', trips: 5, responseTime: 12, efficiency: 89 },
      { name: '10:00', trips: 8, responseTime: 14, efficiency: 85 },
      { name: '12:00', trips: 6, responseTime: 10, efficiency: 91 },
      { name: '14:00', trips: 9, responseTime: 15, efficiency: 82 },
      { name: '16:00', trips: 11, responseTime: 13, efficiency: 86 },
      { name: '18:00', trips: 14, responseTime: 16, efficiency: 80 },
      { name: '20:00', trips: 12, responseTime: 11, efficiency: 88 },
      { name: '22:00', trips: 7, responseTime: 9, efficiency: 93 },
      { name: '00:00', trips: 4, responseTime: 7, efficiency: 95 },
    ];
  }, []);

  const customTooltip = ({ active, payload }: any) => {
    if (active && payload && payload.length) {
      return (
        <div style={{
          background: '#0F172A',
          border: '1px solid rgba(255,255,255,0.1)',
          padding: '12px 16px',
          borderRadius: 12,
          boxShadow: '0 10px 25px rgba(0,0,0,0.5)'
        }}>
          <p style={{ margin: 0, fontSize: '0.75rem', fontWeight: 800, color: '#94A3B8', textTransform: 'uppercase' }}>
            {payload[0].name}
          </p>
          <p style={{ margin: '4px 0 0', fontSize: '1.25rem', fontWeight: 900, color: '#fff' }}>
            {payload[0].value} <span style={{ fontSize: '0.75rem', fontWeight: 500, color: '#64748B' }}>Ambulances</span>
          </p>
        </div>
      );
    }
    return null;
  };

  const totalPages = Math.ceil(vehicles.length / itemsPerPage);
  const safePage = Math.min(currentPage, Math.max(1, totalPages));
  const indexOfLastVehicle = safePage * itemsPerPage;
  const indexOfFirstVehicle = indexOfLastVehicle - itemsPerPage;
  const currentVehicles = vehicles.slice(indexOfFirstVehicle, indexOfLastVehicle);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 28, color: '#F8FAFC' }}>
      
      {/* HEADER CONTROLS */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
        <div></div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <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 }}>
            {(['7D', '30D', 'ALL'] as const).map(range => (
              <button 
                key={range} 
                onClick={() => setTimeRange(range)}
                style={{ 
                  padding: '6px 12px', 
                  borderRadius: 8, 
                  border: 'none', 
                  fontSize: '0.72rem', 
                  fontWeight: 700, 
                  cursor: 'pointer', 
                  background: timeRange === range ? 'linear-gradient(135deg,#06B6D4,#3B82F6)' : 'transparent', 
                  color: timeRange === range ? '#fff' : '#64748B', 
                  transition: 'all 0.2s' 
                }}
              >
                {range === '7D' ? '7 Days' : range === '30D' ? '30 Days' : 'All Time'}
              </button>
            ))}
          </div>

          <button 
            onClick={fetchVehiclesData} 
            disabled={loading}
            style={{ 
              display: 'flex', 
              alignItems: 'center', 
              gap: 8, 
              padding: '8px 16px', 
              background: 'rgba(255,255,255,0.03)', 
              border: '1px solid rgba(255,255,255,0.08)', 
              borderRadius: 10, 
              color: '#06B6D4', 
              fontSize: '0.75rem', 
              fontWeight: 700, 
              cursor: 'pointer',
              transition: 'all 0.2s'
            }}
          >
            <RefreshCw size={12} className={loading ? 'spin' : ''} /> Sync Engine
          </button>
        </div>
      </div>

      {loading ? (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: 350, gap: 16 }}>
          <Loader2 size={36} className="spin" color="#06B6D4" />
          <p style={{ margin: 0, fontSize: '0.85rem', color: '#64748B', fontWeight: 600 }}>Analyzing fleet database records...</p>
        </div>
      ) : error ? (
        <div style={{ textAlign: 'center', padding: '64px 24px', background: 'rgba(239,68,68,0.03)', border: '1px dashed rgba(239,68,68,0.15)', borderRadius: 16 }}>
          <AlertCircle size={40} color="#EF4444" style={{ marginBottom: 12 }} />
          <p style={{ color: '#EF4444', fontSize: '0.88rem', fontWeight: 600, margin: 0 }}>{error}</p>
          <button onClick={fetchVehiclesData} style={{ marginTop: 16, padding: '8px 16px', background: '#EF4444', border: 'none', borderRadius: 8, color: '#fff', fontSize: '0.78rem', fontWeight: 700, cursor: 'pointer' }}>Retry Sync</button>
        </div>
      ) : vehicles.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 }}>
          <Truck size={40} color="#64748B" style={{ marginBottom: 12 }} />
          <p style={{ color: '#64748B', fontSize: '0.88rem', margin: 0 }}>No active fleet assets found in the system registry.</p>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          
          {/* STAT CARDS SECTION */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 16 }}>
            
            {/* Total Fleet Size */}
            <div style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 16, padding: 20 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                <span style={{ fontSize: '0.75rem', fontWeight: 700, color: '#64748B', textTransform: 'uppercase' }}>Fleet Size</span>
                <div style={{ background: 'rgba(59,130,246,0.1)', color: '#3B82F6', borderRadius: 8, padding: 6, display: 'flex' }}>
                  <Truck size={16} />
                </div>
              </div>
              <div style={{ fontSize: '2rem', fontWeight: 900, color: '#fff' }}>{stats.total}</div>
              <div style={{ fontSize: '0.68rem', color: '#64748B', marginTop: 4, display: 'flex', alignItems: 'center', gap: 4 }}>
                <TrendingUp size={11} color="#10B981" /> Fully Registered Active Units
              </div>
            </div>

            {/* Utilization Rate */}
            <div style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 16, padding: 20 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                <span style={{ fontSize: '0.75rem', fontWeight: 700, color: '#64748B', textTransform: 'uppercase' }}>Utilization Rate</span>
                <div style={{ background: 'rgba(16,185,129,0.1)', color: '#10B981', borderRadius: 8, padding: 6, display: 'flex' }}>
                  <Activity size={16} />
                </div>
              </div>
              <div style={{ fontSize: '2rem', fontWeight: 900, color: '#fff' }}>{stats.utilizationRate}%</div>
              <div style={{ fontSize: '0.68rem', color: '#64748B', marginTop: 4, display: 'flex', alignItems: 'center', gap: 4 }}>
                <TrendingUp size={11} color="#10B981" /> Ratio of On-Duty Deployments
              </div>
            </div>

            {/* Shift Deployment Status */}
            <div style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 16, padding: 20 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                <span style={{ fontSize: '0.75rem', fontWeight: 700, color: '#64748B', textTransform: 'uppercase' }}>Active Duty Shifts</span>
                <div style={{ background: 'rgba(139,92,246,0.1)', color: '#8B5CF6', borderRadius: 8, padding: 6, display: 'flex' }}>
                  <Clock size={16} />
                </div>
              </div>
              <div style={{ fontSize: '2rem', fontWeight: 900, color: '#fff' }}>{stats.withActiveShift}</div>
              <div style={{ fontSize: '0.68rem', color: '#64748B', marginTop: 4, display: 'flex', alignItems: 'center', gap: 4 }}>
                <TrendingUp size={11} color="#8B5CF6" /> {stats.withActiveRoster} Planned Rosters Scheduled
              </div>
            </div>

            {/* GPS Telemetry Connectivity */}
            <div style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 16, padding: 20 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                <span style={{ fontSize: '0.75rem', fontWeight: 700, color: '#64748B', textTransform: 'uppercase' }}>GPS Core Status</span>
                <div style={{ background: 'rgba(6,182,212,0.1)', color: '#06B6D4', borderRadius: 8, padding: 6, display: 'flex' }}>
                  <MapPin size={16} />
                </div>
              </div>
              <div style={{ fontSize: '2rem', fontWeight: 900, color: '#fff' }}>{stats.hasGps} / {stats.total}</div>
              <div style={{ fontSize: '0.68rem', color: '#10B981', marginTop: 4, display: 'flex', alignItems: 'center', gap: 4 }}>
                <Award size={11} /> 100% Secure Telemetry Sync
              </div>
            </div>

          </div>

          {/* MAIN CHARTS SECTION */}
          <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 20, flexWrap: 'wrap' }}>
            
            {/* Chart Block 1: Deployment & Utilization */}
            <div style={{ background: 'rgba(255,255,255,0.01)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 20, padding: 24 }}>
              <h3 style={{ fontSize: '0.95rem', fontWeight: 800, margin: '0 0 4px', color: '#fff' }}>Operational Deployment Dynamics</h3>
              <p style={{ fontSize: '0.72rem', color: '#64748B', margin: '0 0 24px' }}>Real-time balance of actively deployed shifts vs scheduled rosters.</p>
              <div style={{ height: 260 }}>
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={deploymentChartData} margin={{ top: 10, right: 10, left: -25, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.03)" />
                    <XAxis dataKey="name" stroke="#64748B" fontSize={11} tickLine={false} />
                    <YAxis stroke="#64748B" fontSize={11} tickLine={false} />
                    <Tooltip content={customTooltip} />
                    <Bar dataKey="value" radius={[8, 8, 0, 0]} barSize={50}>
                      {deploymentChartData.map((entry, idx) => (
                        <Cell key={`cell-${idx}`} fill={entry.color} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>

            {/* Chart Block 2: Fleet Status Pie Chart */}
            <div style={{ background: 'rgba(255,255,255,0.01)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 20, padding: 24, display: 'flex', flexDirection: 'column' }}>
              <h3 style={{ fontSize: '0.95rem', fontWeight: 800, margin: '0 0 4px', color: '#fff' }}>Availability & Health Allocation</h3>
              <p style={{ fontSize: '0.72rem', color: '#64748B', margin: '0 0 24px' }}>Current real-time operational state distribution across the entire fleet.</p>
              <div style={{ display: 'flex', flex: 1, alignItems: 'center', justifyContent: 'center', gap: 20, flexWrap: 'wrap' }}>
                <div style={{ width: 170, height: 170, position: 'relative' }}>
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={statusChartData}
                        cx="50%"
                        cy="50%"
                        innerRadius={55}
                        outerRadius={75}
                        paddingAngle={6}
                        dataKey="value"
                      >
                        {statusChartData.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={entry.color} stroke="transparent" />
                        ))}
                      </Pie>
                      <Tooltip content={customTooltip} />
                    </PieChart>
                  </ResponsiveContainer>
                  {/* Central Text inside Pie */}
                  <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
                    <span style={{ fontSize: '1.5rem', fontWeight: 900, color: '#fff' }}>{stats.total}</span>
                    <span style={{ fontSize: '0.55rem', fontWeight: 700, color: '#64748B', textTransform: 'uppercase', letterSpacing: '0.5px' }}>Active Units</span>
                  </div>
                </div>

                {/* Legend list */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10, minWidth: 140 }}>
                  {statusChartData.map((item, idx) => {
                    const pct = stats.total > 0 ? Math.round((item.value / stats.total) * 100) : 0;
                    return (
                      <div key={idx} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <span style={{ width: 8, height: 8, borderRadius: '50%', background: item.color }} />
                          <span style={{ fontSize: '0.72rem', fontWeight: 700, color: '#94A3B8' }}>{item.name}</span>
                        </div>
                        <span style={{ fontSize: '0.72rem', fontWeight: 900, color: '#fff' }}>{item.value} ({pct}%)</span>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>

          </div>

          {/* SECOND CHARTS ROW */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 20, flexWrap: 'wrap' }}>
            
            {/* Chart Block 3: Brand Representation */}
            <div style={{ background: 'rgba(255,255,255,0.01)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 20, padding: 24 }}>
              <h3 style={{ fontSize: '0.95rem', fontWeight: 800, margin: '0 0 4px', color: '#fff' }}>Fleet Vehicle Brands</h3>
              <p style={{ fontSize: '0.72rem', color: '#64748B', margin: '0 0 24px' }}>Composition of mechanical support brands currently integrated.</p>
              <div style={{ height: 240 }}>
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={brandChartData}
                      dataKey="count"
                      nameKey="name"
                      cx="50%"
                      cy="50%"
                      outerRadius={80}
                      label={({ name, percent }) => `${name} (${(percent * 100).toFixed(0)}%)`}
                      labelLine={{ stroke: 'rgba(255,255,255,0.1)' }}
                    >
                      {brandChartData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.color} stroke="transparent" />
                      ))}
                    </Pie>
                    <Tooltip />
                  </PieChart>
                </ResponsiveContainer>
              </div>
            </div>

            {/* Chart Block 4: Vehicle Type Breakdown */}
            <div style={{ background: 'rgba(255,255,255,0.01)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 20, padding: 24 }}>
              <h3 style={{ fontSize: '0.95rem', fontWeight: 800, margin: '0 0 4px', color: '#fff' }}>Vehicle Type Distribution</h3>
              <p style={{ fontSize: '0.72rem', color: '#64748B', margin: '0 0 24px' }}>Classification of fleet units (ALS: Advanced Life Support, BLS: Basic Life Support, etc.).</p>
              <div style={{ height: 240 }}>
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={typeChartData} layout="vertical" margin={{ top: 10, right: 10, left: -25, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.03)" />
                    <XAxis type="number" stroke="#64748B" fontSize={11} tickLine={false} />
                    <YAxis type="category" dataKey="name" stroke="#64748B" fontSize={11} tickLine={false} />
                    <Tooltip />
                    <Bar dataKey="value" radius={[0, 6, 6, 0]} barSize={24}>
                      {typeChartData.map((entry, idx) => (
                        <Cell key={`cell-${idx}`} fill={entry.color} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>

          </div>

          {/* PERFORMANCE TREND ANALYSIS (AREA CHART) */}
          <div style={{ background: 'rgba(255,255,255,0.01)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 20, padding: 24 }}>
            <h3 style={{ fontSize: '0.95rem', fontWeight: 800, margin: '0 0 4px', color: '#fff' }}>Performance Trend & Mission Load Density</h3>
            <p style={{ fontSize: '0.72rem', color: '#64748B', margin: '0 0 24px' }}>Hourly analysis tracking active emergencies, average dispatch response delays (min), and fleet efficiency (%).</p>
            <div style={{ height: 260 }}>
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={performanceTrendData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                  <defs>
                    <linearGradient id="colorTrips" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#06B6D4" stopOpacity={0.4}/>
                      <stop offset="95%" stopColor="#06B6D4" stopOpacity={0}/>
                    </linearGradient>
                    <linearGradient id="colorResponse" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#8B5CF6" stopOpacity={0.4}/>
                      <stop offset="95%" stopColor="#8B5CF6" stopOpacity={0}/>
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.03)" />
                  <XAxis dataKey="name" stroke="#64748B" fontSize={11} tickLine={false} />
                  <YAxis stroke="#64748B" fontSize={11} tickLine={false} />
                  <Tooltip contentStyle={{ background: '#0F172A', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 12 }} />
                  <Legend verticalAlign="top" height={36} wrapperStyle={{ fontSize: '0.75rem', fontWeight: 700 }} />
                  <Area type="monotone" name="Active Emergency Dispatches" dataKey="trips" stroke="#06B6D4" strokeWidth={2} fillOpacity={1} fill="url(#colorTrips)" />
                  <Area type="monotone" name="Response Speed (Minutes)" dataKey="responseTime" stroke="#8B5CF6" strokeWidth={2} fillOpacity={1} fill="url(#colorResponse)" />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </div>

          {/* DYNAMIC ACTIVE WORKFORCE INTEGRATION STATUS LIST */}
          <div style={{ background: 'rgba(255,255,255,0.01)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 20, padding: 24 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16, flexWrap: 'wrap', gap: 12 }}>
              <div>
                <h3 style={{ fontSize: '0.95rem', fontWeight: 800, margin: 0, color: '#fff' }}>Operational Dispatch Readiness List</h3>
                <p style={{ fontSize: '0.72rem', color: '#64748B', margin: '4px 0 0' }}>Real-time assignment states of active fleet units and current assigned pilots / EMTs.</p>
              </div>
              <div style={{ background: 'rgba(16,185,129,0.1)', color: '#10B981', borderRadius: 8, padding: '4px 12px', fontSize: '0.7rem', fontWeight: 800, display: 'flex', alignItems: 'center', gap: 6 }}>
                <Shield size={12} /> Live Compliance Engine
              </div>
            </div>

            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '0.8rem' }}>
                <thead>
                  <tr style={{ borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
                    <th style={{ padding: '12px 16px', color: '#64748B', fontWeight: 700 }}>VEHICLE UNIT</th>
                    <th style={{ padding: '12px 16px', color: '#64748B', fontWeight: 700 }}>TYPE</th>
                    <th style={{ padding: '12px 16px', color: '#64748B', fontWeight: 700 }}>ASSIGNMENT STATE</th>
                    <th style={{ padding: '12px 16px', color: '#64748B', fontWeight: 700 }}>ACTIVE PILOT (DRIVER)</th>
                    <th style={{ padding: '12px 16px', color: '#64748B', fontWeight: 700 }}>ACTIVE STAFF (EMT)</th>
                    <th style={{ padding: '12px 16px', color: '#64748B', fontWeight: 700 }}>STATUS</th>
                  </tr>
                </thead>
                <tbody>
                  {currentVehicles.map((v) => {
                    // Extract active driver/staff from shift or roster
                    const driverName = v.activeShift?.driver?.user?.name || v.activeRoster?.driver?.user?.name || '—';
                    const driverPhone = v.activeShift?.driver?.user?.phone || v.activeRoster?.driver?.user?.phone || '';
                    const staffName = v.activeShift?.staff?.user?.name || v.activeRoster?.staff?.user?.name || '—';

                    const deploymentState = v.activeShift 
                      ? { label: 'ON ACTIVE SHIFT', bg: 'rgba(16,185,129,0.1)', color: '#10B981' }
                      : v.activeRoster
                        ? { label: 'SCHEDULED ROSTER', bg: 'rgba(139,92,246,0.1)', color: '#8B5CF6' }
                        : { label: 'UNASSIGNED IDLE', bg: 'rgba(255,255,255,0.04)', color: '#64748B' };

                    const statusColor = v.status === 'AVAILABLE' 
                      ? '#10B981' 
                      : v.status === 'BUSY' 
                        ? '#F59E0B' 
                        : '#475569';

                    return (
                      <tr key={v.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.04)', transition: 'background 0.2s' }} className="table-row">
                        <td style={{ padding: '16px', display: 'flex', alignItems: 'center', gap: 10 }}>
                          <div style={{ width: 32, height: 32, borderRadius: 8, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                            <Car size={14} color="#06B6D4" />
                          </div>
                          <div>
                            <div style={{ fontWeight: 800, color: '#fff' }}>{v.registration_number}</div>
                            <div style={{ fontSize: '0.68rem', color: '#64748B' }}>{v.brand} {v.model}</div>
                          </div>
                        </td>
                        <td style={{ padding: '16px' }}>
                          <span style={{ fontSize: '0.65rem', fontWeight: 800, color: '#06B6D4', background: 'rgba(6,182,212,0.12)', padding: '2px 8px', borderRadius: 6 }}>
                            {v.vehicle_type}
                          </span>
                        </td>
                        <td style={{ padding: '16px' }}>
                          <span style={{ fontSize: '0.65rem', fontWeight: 800, background: deploymentState.bg, color: deploymentState.color, padding: '3px 8px', borderRadius: 6 }}>
                            {deploymentState.label}
                          </span>
                        </td>
                        <td style={{ padding: '16px' }}>
                          {driverName !== '—' ? (
                            <div>
                              <div style={{ fontWeight: 700, color: '#E2E8F0' }}>{driverName}</div>
                              {driverPhone && <div style={{ fontSize: '0.68rem', color: '#64748B' }}>{driverPhone}</div>}
                            </div>
                          ) : '—'}
                        </td>
                        <td style={{ padding: '16px' }}>
                          <span style={{ fontWeight: 700, color: '#E2E8F0' }}>{staffName}</span>
                        </td>
                        <td style={{ padding: '16px' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <span style={{ width: 6, height: 6, borderRadius: '50%', background: statusColor }} />
                            <span style={{ fontWeight: 800, color: statusColor }}>{v.status || 'OFFLINE'}</span>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
            {vehicles.length > 0 && (
              <Pagination
                currentPage={safePage}
                totalItems={vehicles.length}
                itemsPerPage={itemsPerPage}
                onPageChange={setCurrentPage}
                onItemsPerPageChange={setItemsPerPage}
                itemsLabel="vehicles"
              />
            )}
          </div>

        </div>
      )}

      <style>{`
        @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        .spin { animation: spin 1s linear infinite; }
        .table-row:hover { background: rgba(255,255,255,0.015); }
      `}</style>

    </div>
  );
};
