import React, { useState, useEffect, useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';
import { 
  Activity, 
  Truck, 
  Zap, 
  ShieldCheck, 
  MapPin, 
  Clock, 
  Navigation, 
  AlertTriangle,
  Fuel,
  Gauge,
  Thermometer,
  Wind,
  Bell,
  Settings,
  ChevronRight,
  LayoutGrid,
  Route as RouteIcon,
  Users,
  Search,
  CheckCircle2,
  ShoppingCart
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { Card, StatCard } from '../components/Common';
import { fleetApi } from '../api/fleet';
import { incidentsApi } from '../api/incidents';
import type { Incident } from '../api/types';
import { 
  AreaChart, 
  Area, 
  Tooltip, 
  ResponsiveContainer,
  BarChart,
  Bar,
  XAxis,
  YAxis
} from 'recharts';

// --- NEW FLEET MODULES ---
import { FleetAssets } from './fleet/FleetAssets';
import { FleetPersonnel } from './fleet/FleetPersonnel';
import { FleetInventory } from './fleet/FleetInventory';
import { FleetScheduling } from './fleet/FleetScheduling';

// --- MOCK DATA FOR THE ENHANCED FEEL ---
const MOCK_VEHICLES = [
  { id: 'V001', number: 'TN-01-AM-1024', status: 'EN_ROUTE', speed: 45, fuel: 82, lat: 13.0827, lng: 80.2707, type: 'ALS' },
  { id: 'V002', number: 'TN-05-AM-5521', status: 'IDLE', speed: 0, fuel: 65, lat: 13.0067, lng: 80.2575, type: 'BLS' },
  { id: 'V003', number: 'TN-07-AM-1122', status: 'TRANSPORTING', speed: 52, fuel: 45, lat: 12.9667, lng: 80.2475, type: 'TRANSFER' },
  { id: 'V004', number: 'TN-09-AM-9988', status: 'AT_SCENE', speed: 0, fuel: 78, lat: 12.9941, lng: 80.1709, type: 'AIR' },
];

const PERFORMANCE_DATA = [
  { time: '08:00', trips: 12, response: 14 },
  { time: '10:00', trips: 18, response: 12 },
  { time: '12:00', trips: 25, response: 18 },
  { time: '14:00', trips: 22, response: 15 },
  { time: '16:00', trips: 30, response: 22 },
  { time: '18:00', trips: 28, response: 19 },
];

// --- LIVE MAP COMPONENT ---
const CommandMap: React.FC<{ vehicles: any[] }> = ({ vehicles }) => {
  const [L, setL] = useState<any>(null);
  const mapRef = React.useRef<any>(null);

  useEffect(() => {
    if (typeof window === 'undefined') return;
    
    const loadLeaflet = () => {
      const leaflet = (window as any).L;
      if (leaflet) {
        setL(leaflet);
        if (!mapRef.current) {
          const m = leaflet.map('fleet-command-map', {
            zoomControl: false,
            attributionControl: false
          }).setView([13.0827, 80.2707], 12);
          
          leaflet.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
            maxZoom: 20
          }).addTo(m);
          
          mapRef.current = m;
        }
      }
    };

    if (!(window as any).L) {
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
      document.head.appendChild(link);

      const script = document.createElement('script');
      script.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
      script.async = true;
      script.onload = loadLeaflet;
      document.head.appendChild(script);
    } else {
      loadLeaflet();
    }

    return () => {
      if (mapRef.current) {
        mapRef.current.remove();
        mapRef.current = null;
      }
    };
  }, []);

  useEffect(() => {
    if (!L || !mapRef.current) return;
    const map = mapRef.current;
    
    vehicles.forEach(v => {
      const getStatusColor = (status: string) => {
        switch (status) {
          case 'IDLE': return '#94A3B8';
          case 'EN_ROUTE': return '#3B82F6';
          case 'AT_SCENE': return '#F59E0B';
          case 'TRANSPORTING': return '#EF4444';
          case 'AT_HOSPITAL': return '#A855F7';
          case 'BREAKDOWN': return '#000000';
          case 'OFF_DUTY': return '#FFFFFF';
          default: return '#3B82F6';
        }
      };
      const color = getStatusColor(v.status);
      const icon = L.divIcon({
        className: 'custom-marker',
        html: `<div style="background: ${color}; width: 24px; height: 24px; border-radius: 50% 50% 50% 0; transform: rotate(-45deg); display: flex; align-items: center; justify-content: center; box-shadow: 0 0 15px ${color}; border: 2px solid #fff;">
                <div style="transform: rotate(45deg); color: #fff;"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-1.1 0-2 .9-2 2v9c0 .6.4 1 1 1h2"/><circle cx="7" cy="17" r="2"/><path d="M9 17h6"/><circle cx="17" cy="17" r="2"/></svg></div>
              </div>`,
        iconSize: [24, 24],
        iconAnchor: [12, 24]
      });
      L.marker([v.lat, v.lng], { icon }).addTo(map).bindPopup(`<b>${v.number}</b><br/>Status: ${v.status}`);
    });
  }, [L, vehicles]);

  return <div id="fleet-command-map" style={{ height: '100%', minHeight: '400px', borderRadius: '16px' }} />;
};

export const FleetOperatorDashboard: React.FC = () => {
  const [searchParams] = useSearchParams();
  const activeTab = searchParams.get('tab') || 'overview';
  
  const [isLoading, setIsLoading] = useState(true);
  const [incidents, setIncidents] = useState<Incident[]>([]);
  const [vehicles, setVehicles] = useState(MOCK_VEHICLES);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const token = localStorage.getItem('teleems_token') || '';
        const res = await incidentsApi.getIncidents({}, token);
        if (res && res.data) setIncidents(res.data.slice(0, 5));
      } catch (err) {
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchData();
  }, []);

  const menuItems = [
    { id: 'overview', label: 'Command Center', icon: LayoutGrid },
    { id: 'assets', label: 'Fleet Assets', icon: Truck },
    { id: 'personnel', label: 'Personnel Hub', icon: Users },
    { id: 'scheduling', label: 'Mission Control', icon: Navigation },
    { id: 'inventory', label: 'Supply Chain', icon: ShoppingCart },
    { id: 'analytics', label: 'Fleet Intel', icon: Activity },
  ];

  const renderContent = () => {
    switch (activeTab) {
      case 'overview':
        return (
          <div className="animate-in fade-in slide-in-from-bottom-4 duration-500">
            {/* Stats Grid */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '24px', marginBottom: '32px' }}>
              <StatCard label="Live Fleet" value="48" icon={Truck} glowColor="cyan" trend={{ value: '12%', isUp: true }} />
              <StatCard label="Active Trips" value="12" icon={Activity} glowColor="green" pulse />
              <StatCard label="Avg Response" value="8.4m" icon={Zap} glowColor="amber" trend={{ value: '0.5m', isUp: false }} />
              <StatCard label="Compliance" value="99.2%" icon={ShieldCheck} glowColor="cyan" />
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '24px' }}>
              {/* Left Column: Map and Fleet List */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
                <Card style={{ height: '500px', padding: 0, overflow: 'hidden', border: '1px solid rgba(59, 130, 246, 0.3)', position: 'relative' }}>
                  <CommandMap vehicles={vehicles} />
                  <div style={{ position: 'absolute', top: '20px', left: '20px', zIndex: 1000 }}>
                    <div className="glass" style={{ padding: '12px', borderRadius: '12px', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px', border: '1px solid rgba(255,255,255,0.1)' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#3B82F6' }}></div>
                        <span style={{ fontSize: '0.65rem', fontWeight: 600 }}>EN ROUTE</span>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#94A3B8' }}></div>
                        <span style={{ fontSize: '0.65rem', fontWeight: 600 }}>IDLE</span>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#F59E0B' }}></div>
                        <span style={{ fontSize: '0.65rem', fontWeight: 600 }}>AT SCENE</span>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#EF4444' }}></div>
                        <span style={{ fontSize: '0.65rem', fontWeight: 600 }}>TRANSPORTING</span>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#A855F7' }}></div>
                        <span style={{ fontSize: '0.65rem', fontWeight: 600 }}>HOSPITAL</span>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#000000' }}></div>
                        <span style={{ fontSize: '0.65rem', fontWeight: 600 }}>BREAKDOWN</span>
                      </div>
                    </div>
                  </div>
                </Card>

                <Card title="Live Fleet Telemetry">
                  <div className="table-container no-scrollbar" style={{ maxHeight: '300px', overflowY: 'auto' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                      <thead>
                        <tr style={{ borderBottom: '1px solid rgba(255,255,255,0.1)', textAlign: 'left' }}>
                          <th style={{ padding: '12px', fontSize: '0.75rem', textTransform: 'uppercase', opacity: 0.5 }}>Vehicle</th>
                          <th style={{ padding: '12px', fontSize: '0.75rem', textTransform: 'uppercase', opacity: 0.5 }}>Status</th>
                          <th style={{ padding: '12px', fontSize: '0.75rem', textTransform: 'uppercase', opacity: 0.5 }}>Speed</th>
                          <th style={{ padding: '12px', fontSize: '0.75rem', textTransform: 'uppercase', opacity: 0.5 }}>Fuel</th>
                          <th style={{ padding: '12px', fontSize: '0.75rem', textTransform: 'uppercase', opacity: 0.5 }}>Actions</th>
                        </tr>
                      </thead>
                      <tbody>
                        {vehicles.map(v => (
                          <tr key={v.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
                            <td style={{ padding: '16px 12px' }}>
                              <div style={{ fontWeight: 700 }}>{v.number}</div>
                              <div style={{ fontSize: '0.7rem', opacity: 0.5 }}>{v.type} UNIT</div>
                            </td>
                            <td style={{ padding: '16px 12px' }}>
                              <span style={{ 
                                fontSize: '0.65rem', 
                                fontWeight: 900, 
                                padding: '4px 8px', 
                                borderRadius: '4px',
                                background: v.status === 'IDLE' ? 'rgba(148, 163, 184, 0.1)' : 'rgba(59, 130, 246, 0.1)',
                                color: v.status === 'IDLE' ? '#94A3B8' : 'var(--accent-cyan)',
                                border: `1px solid ${v.status === 'IDLE' ? 'rgba(148, 163, 184, 0.2)' : 'rgba(59, 130, 246, 0.2)'}`
                              }}>{v.status}</span>
                            </td>
                            <td style={{ padding: '16px 12px' }} className="mono">{v.speed} km/h</td>
                            <td style={{ padding: '16px 12px' }}>
                              <div style={{ width: '100px', height: '6px', background: 'rgba(255,255,255,0.1)', borderRadius: '3px', overflow: 'hidden' }}>
                                <div style={{ width: `${v.fuel}%`, height: '100%', background: v.fuel < 30 ? 'var(--alert-red)' : 'var(--accent-green)' }}></div>
                              </div>
                            </td>
                            <td style={{ padding: '16px 12px' }}>
                              <button className="btn-ghost-sm"><Navigation size={14} /></button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </Card>
              </div>

              {/* Right Column: Performance and Incidents */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
                <Card title="Operational Load">
                  <div style={{ height: '200px', width: '100%', position: 'relative' }}>
                    <ResponsiveContainer width="100%" height="100%" minWidth={0} minHeight={0}>
                      <AreaChart data={PERFORMANCE_DATA}>
                        <defs>
                          <linearGradient id="colorTrips" x1="0" y1="0" x2="0" y2="1">
                            <stop offset="5%" stopColor="var(--accent-cyan)" stopOpacity={0.3}/>
                            <stop offset="95%" stopColor="var(--accent-cyan)" stopOpacity={0}/>
                          </linearGradient>
                        </defs>
                        <Tooltip 
                          contentStyle={{ background: '#1E293B', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                          itemStyle={{ color: 'var(--accent-cyan)' }}
                        />
                        <Area type="monotone" dataKey="trips" stroke="var(--accent-cyan)" fillOpacity={1} fill="url(#colorTrips)" />
                      </AreaChart>
                    </ResponsiveContainer>
                  </div>
                </Card>

                <Card title="Active Incident Feed">
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                    {incidents.length > 0 ? incidents.map(inc => (
                      <div key={inc.id} className="glass hover-glow" style={{ padding: '16px', borderRadius: '12px', borderLeft: `4px solid ${inc.severity === 'CRITICAL' ? 'var(--alert-red)' : 'var(--accent-cyan)'}` }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                          <span className="mono" style={{ fontSize: '0.8rem', fontWeight: 800 }}>#{inc.id.split('-').pop()?.toUpperCase()}</span>
                          <span style={{ fontSize: '0.6rem', color: 'var(--alert-red)', fontWeight: 900 }}>{inc.severity}</span>
                        </div>
                        <div style={{ fontSize: '0.875rem', fontWeight: 600, marginBottom: '4px' }}>{inc.category}</div>
                        <div style={{ fontSize: '0.75rem', opacity: 0.6, display: 'flex', alignItems: 'center', gap: '4px' }}>
                          <MapPin size={12} /> {inc.address}
                        </div>
                      </div>
                    )) : (
                      <div style={{ textAlign: 'center', padding: '20px', opacity: 0.5 }}>No active incidents</div>
                    )}
                  </div>
                  <button style={{ width: '100%', marginTop: '16px', padding: '10px', background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px', color: 'var(--accent-cyan)', fontWeight: 700, cursor: 'pointer' }}>
                    VIEW ALL INCIDENTS
                  </button>
                </Card>

                <Card title="Fleet Health Indicators">
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
                    <div style={{ padding: '16px', background: 'rgba(255,255,255,0.02)', borderRadius: '12px', textAlign: 'center' }}>
                      <Gauge size={24} color="var(--accent-cyan)" style={{ marginBottom: '8px' }} />
                      <div style={{ fontSize: '1.25rem', fontWeight: 800 }}>82%</div>
                      <div style={{ fontSize: '0.65rem', opacity: 0.5 }}>AVAILABILITY</div>
                    </div>
                    <div style={{ padding: '16px', background: 'rgba(255,255,255,0.02)', borderRadius: '12px', textAlign: 'center' }}>
                      <Fuel size={24} color="var(--accent-green)" style={{ marginBottom: '8px' }} />
                      <div style={{ fontSize: '1.25rem', fontWeight: 800 }}>94%</div>
                      <div style={{ fontSize: '0.65rem', opacity: 0.5 }}>FUEL READINESS</div>
                    </div>
                  </div>
                </Card>
              </div>
            </div>
          </div>
        );
      case 'assets':
        return <FleetAssets />;
      case 'personnel':
        return <FleetPersonnel />;
      case 'scheduling':
        return <FleetScheduling />;
      case 'inventory':
        return <FleetInventory />;
      case 'analytics':
        return <div className="glass" style={{ padding: '40px', textAlign: 'center', color: 'var(--text-secondary)' }}>Fleet Intelligence Reports Loading...</div>;
      default:
        return null;
    }
  };

  return (
    <div className="fleet-operator-dashboard" style={{ 
      background: '#020617', 
      color: '#F8FAFC', 
      minHeight: '100vh',
      fontFamily: "'Inter', sans-serif",
      display: 'flex',
      flexDirection: 'column'
    }}>
      {/* Main Content Area */}
      <div style={{ 
        flex: 1, 
        padding: '32px',
        maxWidth: '100%'
      }}>
        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '32px' }}>
          <div>
            <h1 style={{ fontSize: '2.5rem', fontWeight: 900, letterSpacing: '-0.05em', color: 'var(--accent-cyan)', textTransform: 'uppercase' }}>
              {menuItems.find(m => m.id === activeTab)?.label || 'Fleet Command'}
            </h1>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', opacity: 0.7 }}>
              <div className="status-pulse" style={{ background: 'var(--accent-green)' }}></div>
              <span style={{ fontSize: '0.875rem' }}>Strategic Operations • Live Platform Telemetry</span>
            </div>
          </div>
          <div style={{ display: 'flex', gap: '12px' }}>
            <div style={{ background: 'rgba(255,255,255,0.05)', padding: '8px 16px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.1)', display: 'flex', alignItems: 'center', gap: '12px' }}>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: '0.65rem', textTransform: 'uppercase', opacity: 0.5 }}>Tactical Time</div>
                <div style={{ fontWeight: 700 }}>{new Date().toLocaleTimeString()}</div>
              </div>
              <Clock size={20} color="var(--accent-cyan)" />
            </div>
            <button className="btn-icon glass"><Bell size={20} /></button>
            <button className="btn-icon glass"><Settings size={20} /></button>
          </div>
        </div>

        {renderContent()}
      </div>
    </div>
  );
};
