import React, { useState } from 'react';
import { 
  Calendar, 
  Download, 
  FileText, 
  ChevronDown, 
  TrendingUp, 
  Activity, 
  Map as MapIcon, 
  BarChart3, 
  PieChart as PieChartIcon, 
  Clock, 
  Filter,
  Users,
  Building2,
  Package,
  Layers,
  MapPin,
  Crosshair
} from 'lucide-react';
import { Card } from '../components/Common';
import { 
  AreaChart, 
  Area, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer,
  LineChart,
  Line,
  BarChart,
  Bar,
  Cell,
  PieChart,
  Pie
} from 'recharts';
import { motion, AnimatePresence } from 'framer-motion';

const incidentTrend = [
  { day: 'Mon', count: 42, critical: 12 },
  { day: 'Tue', count: 38, critical: 8 },
  { day: 'Wed', count: 55, critical: 18 },
  { day: 'Thu', count: 48, critical: 10 },
  { day: 'Fri', count: 70, critical: 25 },
  { day: 'Sat', count: 85, critical: 32 },
  { day: 'Sun', count: 62, critical: 20 },
];

const operatorPerformance = [
  { name: 'Lifeline', trips: 1450, utl: 85 },
  { name: 'Apex', trips: 1280, utl: 78 },
  { name: 'Mercy', trips: 920, utl: 72 },
  { name: 'CureMove', trips: 1100, utl: 81 },
];

const triageDistribution = [
  { name: 'Immediate (Red)', value: 15, color: '#ff3b3b' },
  { name: 'Urgent (Orange)', value: 25, color: '#ffb800' },
  { name: 'Minor (Green)', value: 45, color: '#00ff88' },
  { name: 'Non-Emg (White)', value: 10, color: '#E2E8F0' },
  { name: 'IFT (Blue)', value: 5, color: '#3B82F6' },
];

type AnalyticsView = 'COMM_CENTER' | 'AGGREGATORS_FLEET' | 'HOSPITALS_CLINICAL' | 'INVENTORY_RESOURCES';

export const AnalyticsReports: React.FC = () => {
  const [activeView, setActiveView] = useState<AnalyticsView>('COMM_CENTER');

  return (
    <div className="page-container" style={{ display: 'flex', flexDirection: 'column', gap: '32px' }}>
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <h2 style={{ fontSize: '2.5rem', fontWeight: 900, background: 'linear-gradient(90deg, var(--accent-blue), var(--text-primary))', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>
            Platform Intelligence
          </h2>
          <p style={{ color: 'var(--text-secondary)', fontSize: '0.9rem', marginTop: '4px' }}>
            Real-time KPIs, cross-entity performance metrics, and geographic incident heatmaps.
          </p>
        </div>
        
        <div style={{ display: 'flex', gap: '16px' }}>
           <div className="glass" style={{ padding: '4px', borderRadius: '12px', display: 'flex', gap: '4px', background: 'rgba(0,0,0,0.03)' }}>
             {(['COMM_CENTER', 'AGGREGATORS_FLEET', 'HOSPITALS_CLINICAL', 'INVENTORY_RESOURCES'] as AnalyticsView[]).map(view => (
               <button
                 key={view}
                 onClick={() => setActiveView(view)}
                 style={{ 
                   padding: '10px 16px', borderRadius: '8px', border: 'none', 
                   background: activeView === view ? 'var(--accent-blue)' : 'transparent',
                   color: activeView === view ? '#fff' : 'var(--text-secondary)',
                   fontWeight: 700, cursor: 'pointer', fontSize: '0.7rem'
                 }}>
                 {view.replace('_', ' ')}
               </button>
             ))}
           </div>
           <button style={{ padding: '12px 24px', background: 'rgba(59, 130, 246, 0.1)', border: '1px solid var(--accent-blue)', borderRadius: '10px', color: 'var(--accent-blue)', fontWeight: 800, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '10px', transition: 'all 0.3s ease' }}>
              <Download size={18} /> EXPORT PDF/CSV
           </button>
        </div>
      </header>

      {/* GLOBAL HUD STATS */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '20px' }}>
        {[
          { label: 'Total Incidents', value: '18,242', trend: '+5.2%', color: 'cyan' },
          { label: 'Avg Dispatch Time', value: '1.42m', trend: '-22s', color: 'green' },
          { label: 'Active ePCR Count', value: '4,102', trend: '+12%', color: 'amber' },
          { label: 'Hospital Pre-Alerts', value: '892', trend: '+8%', color: 'cyan' },
          { label: 'System Uptime', value: '99.99%', trend: 'Stable', color: 'green' },
        ].map(stat => (
          <Card key={stat.label} style={{ padding: '20px' }} className={`glow-${stat.color}`}>
            <div style={{ fontSize: '0.65rem', color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>{stat.label}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: '8px', marginTop: '10px' }}>
              <div style={{ fontSize: '1.6rem', fontWeight: 900 }} className="mono">{stat.value}</div>
              <div style={{ fontSize: '0.75rem', color: stat.trend.startsWith('+') ? 'var(--accent-green)' : (stat.trend === 'Stable' ? 'var(--accent-cyan)' : 'var(--alert-red)') }}>{stat.trend}</div>
            </div>
          </Card>
        ))}
      </div>

      <AnimatePresence mode="wait">
         {activeView === 'COMM_CENTER' && (
           <motion.div key="comm" initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -20 }} style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1.8fr 1.2fr', gap: '24px' }}>
                 <Card title="Incident Frequency Trend" subtitle="Daily critical vs standard emergencies.">
                    <div style={{ height: '350px', marginTop: '20px' }}>
                       <ResponsiveContainer width="100%" height={350}>
                          <AreaChart data={incidentTrend}>
                             <defs>
                                <linearGradient id="colorCount" x1="0" y1="0" x2="0" y2="1">
                                   <stop offset="5%" stopColor="var(--accent-cyan)" stopOpacity={0.4}/>
                                   <stop offset="95%" stopColor="var(--accent-cyan)" stopOpacity={0}/>
                                </linearGradient>
                                <linearGradient id="colorCritical" x1="0" y1="0" x2="0" y2="1">
                                   <stop offset="5%" stopColor="var(--alert-red)" stopOpacity={0.4}/>
                                   <stop offset="95%" stopColor="var(--alert-red)" stopOpacity={0}/>
                                </linearGradient>
                             </defs>
                             <CartesianGrid strokeDasharray="3 3" stroke="rgba(0,0,0,0.05)" vertical={false} />
                             <XAxis dataKey="day" stroke="var(--text-secondary)" fontSize={12} tick={{fontWeight: 600}} />
                             <YAxis stroke="var(--text-secondary)" fontSize={12} />
                             <Tooltip contentStyle={{ background: 'var(--base-bg)', border: '1px solid var(--card-border)', borderRadius: '12px' }} />
                             <Area type="monotone" dataKey="count" stroke="var(--accent-cyan)" strokeWidth={3} fillOpacity={1} fill="url(#colorCount)" name="Total Incidents" />
                             <Area type="monotone" dataKey="critical" stroke="var(--alert-red)" strokeWidth={3} fillOpacity={1} fill="url(#colorCritical)" name="Critical (Red)" />
                          </AreaChart>
                       </ResponsiveContainer>
                    </div>
                 </Card>

                 <Card title="Traffic Segmentation" subtitle="Distribution by Triage Category.">
                    <div style={{ height: '350px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                       <ResponsiveContainer width="100%" height={300}>
                          <PieChart>
                             <Pie
                                data={triageDistribution}
                                cx="50%"
                                cy="50%"
                                innerRadius={70}
                                outerRadius={100}
                                paddingAngle={5}
                                dataKey="value"
                             >
                                {triageDistribution.map((entry, index) => (
                                  <Cell key={`cell-${index}`} fill={entry.color} />
                                ))}
                             </Pie>
                             <Tooltip contentStyle={{ background: 'var(--base-bg)', border: '1px solid var(--card-border)', borderRadius: '12px' }} />
                          </PieChart>
                       </ResponsiveContainer>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px', marginTop: '10px' }}>
                       {triageDistribution.map(td => (
                         <div key={td.name} style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: td.color }} />
                            <span style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>{td.name}</span>
                            <span style={{ fontSize: '0.7rem', fontWeight: 800, marginLeft: 'auto' }}>{td.value}%</span>
                         </div>
                       ))}
                    </div>
                 </Card>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '24px' }}>
                 <Card title="Geographic Heatmap" subtitle="Active incident hotspots by district.">
                    <div style={{ height: '220px', background: 'rgba(0,0,0,0.03)', borderRadius: '12px', border: '1px solid var(--card-border)', position: 'relative', overflow: 'hidden' }}>
                       <div style={{ position: 'absolute', inset: 0, opacity: 0.3, background: 'url("https://upload.wikimedia.org/wikipedia/commons/4/4b/Tamil_Nadu_districts_map.svg") center/contain no-repeat' }} />
                       <div style={{ position: 'absolute', top: '20%', left: '45%', width: '40px', height: '40px', background: 'radial-gradient(circle, rgba(255,59,59,0.8) 0%, transparent 70%)' }} />
                       <div style={{ position: 'absolute', top: '50%', left: '30%', width: '30px', height: '30px', background: 'radial-gradient(circle, rgba(59, 130, 246, 0.8) 0%, transparent 70%)' }} />
                       <div style={{ position: 'absolute', bottom: '10px', right: '10px', fontSize: '0.6rem', color: 'var(--text-secondary)', background: 'rgba(255,255,255,0.8)', padding: '4px 8px', borderRadius: '4px' }}>
                          Live Feed: Chennai Hub
                       </div>
                    </div>
                 </Card>
                 
                 <Card title="CCE Performance" subtitle="Average handle time (AHT) per shift.">
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
                       {[
                         { shift: 'Morning (SH1)', aht: '1m 12s', target: '1m 30s', status: 'Optimal' },
                         { shift: 'Afternoon (SH2)', aht: '1m 28s', target: '1m 30s', status: 'Healthy' },
                         { shift: 'Night (SH3)', aht: '1m 45s', target: '1m 30s', status: 'Delayed' },
                       ].map((cce, i) => (
                         <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <div>
                               <div style={{ fontSize: '0.8rem', fontWeight: 800 }}>{cce.shift}</div>
                               <div style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Log: {cce.aht} (Limit: {cce.target})</div>
                            </div>
                            <div style={{ fontSize: '0.75rem', fontWeight: 800, color: cce.status === 'Optimal' ? 'var(--accent-green)' : (cce.status === 'Healthy' ? 'var(--accent-cyan)' : 'var(--alert-red)') }}>{cce.status}</div>
                         </div>
                       ))}
                    </div>
                 </Card>

                 <Card title="Resource Health" subtitle="Mobile medical unit status.">
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                       <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                          <span style={{ fontSize: '0.75rem' }}>ALS Availability</span>
                          <span className="mono" style={{ fontSize: '0.8rem', fontWeight: 800, color: 'var(--accent-cyan)' }}>88%</span>
                       </div>
                       <div style={{ width: '100%', height: '6px', background: 'rgba(0,0,0,0.03)', borderRadius: '3px' }}>
                          <div style={{ width: '88%', height: '100%', background: 'var(--accent-cyan)', borderRadius: '3px' }}></div>
                       </div>
                       <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px', marginTop: '8px' }}>
                          <span style={{ fontSize: '0.75rem' }}>BLS Availability</span>
                          <span className="mono" style={{ fontSize: '0.8rem', fontWeight: 800, color: 'var(--accent-green)' }}>95%</span>
                       </div>
                       <div style={{ width: '100%', height: '6px', background: 'rgba(0,0,0,0.03)', borderRadius: '3px' }}>
                          <div style={{ width: '95%', height: '100%', background: 'var(--accent-green)', borderRadius: '3px' }}></div>
                       </div>
                    </div>
                 </Card>
              </div>
           </motion.div>
         )}

         {activeView === 'AGGREGATORS_FLEET' && (
            <motion.div key="agg" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }}>
               <Card title="Operator Unit Utilization" subtitle="Total trips vs vehicle utilization rate (last 30 days).">
                  <div style={{ height: '400px', marginTop: '24px' }}>
                     <ResponsiveContainer width="100%" height={400}>
                        <BarChart data={operatorPerformance}>
                           <CartesianGrid strokeDasharray="3 3" stroke="rgba(0,0,0,0.05)" vertical={false} />
                           <XAxis dataKey="name" stroke="var(--text-secondary)" fontSize={12} tick={{fontWeight: 700}} />
                           <YAxis yAxisId="left" stroke="var(--text-secondary)" fontSize={12} />
                           <YAxis yAxisId="right" orientation="right" stroke="var(--text-secondary)" fontSize={12} unit="%" />
                           <Tooltip contentStyle={{ background: 'var(--base-bg)', border: '1px solid var(--card-border)', borderRadius: '12px' }} />
                           <Bar yAxisId="left" dataKey="trips" fill="var(--accent-cyan)" radius={[4, 4, 0, 0]} name="Total Trips" barSize={40} />
                           <Line yAxisId="right" type="monotone" dataKey="utl" stroke="var(--accent-green)" strokeWidth={3} name="Utilization (%)" />
                        </BarChart>
                     </ResponsiveContainer>
                  </div>
               </Card>
            </motion.div>
         )}
      </AnimatePresence>
    </div>
  );
};
