import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { 
  TrendingUp, 
  BarChart, 
  PieChart, 
  Clock, 
  Calendar, 
  Download, 
  Filter, 
  Activity, 
  Users, 
  Video, 
  Zap,
  ArrowUpRight,
  ArrowDownRight,
  Search,
  FileBarChart,
  BrainCircuit,
  Database
} from 'lucide-react';
import { 
  AreaChart, 
  Area, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer,
  BarChart as ReBarChart,
  Bar,
  Cell,
  PieChart as RePieChart,
  Pie,
  LineChart,
  Line
} from 'recharts';

export const HospitalAnalytics: React.FC = () => {
  const [timeRange, setTimeRange] = useState('7D');

  const volumeData = [
    { name: '00:00', count: 5, baseline: 4 },
    { name: '04:00', count: 12, baseline: 8 },
    { name: '08:00', count: 28, baseline: 22 },
    { name: '12:00', count: 42, baseline: 35 },
    { name: '16:00', count: 38, baseline: 40 },
    { name: '20:00', count: 22, baseline: 18 },
    { name: '23:59', count: 8, baseline: 6 },
  ];

  const triageData = [
    { name: 'Red (Critical)', value: 25, color: 'hsl(0, 84%, 60%)' },
    { name: 'Yellow (Emergent)', value: 45, color: 'hsl(38, 92%, 50%)' },
    { name: 'Green (Standard)', value: 30, color: 'hsl(142, 70%, 45%)' },
  ];

  const departmentEfficiency = [
    { dept: 'ER', load: 85, cap: 90 },
    { dept: 'ICU', load: 92, cap: 80 },
    { dept: 'Cardio', load: 60, cap: 75 },
    { dept: 'Trauma', load: 78, cap: 85 },
  ];

  return (
    <motion.div 
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      className="module-content analytics-v2"
    >
      <div className="module-header-modern">
        <div className="title-wrap">
          <div className="clinical-intel-badge">
            <BrainCircuit size={16} />
            CONSOLIDATED CLINICAL INTELLIGENCE
          </div>
          <h3>Hospital Command Insights</h3>
        </div>
        <div className="action-area-header">
          <div className="intel-filters">
            {['24H', '7D', '30D', 'ALL'].map(t => (
              <button 
                key={t}
                className={`intel-filter-btn ${timeRange === t ? 'active' : ''}`}
                onClick={() => setTimeRange(t)}
              >
                {t}
              </button>
            ))}
          </div>
          <button className="register-staff-btn-premium">
            <FileBarChart size={18} />
            <span className="hide-mobile">EXTRACT REPORT</span>
          </button>
        </div>
      </div>

      <div className="intelligence-grid">
        {/* Row 1: High Level KPIs */}
        <div className="kpi-strip">
          <div className="kpi-card-modern neon-blue">
            <div className="kpi-icon"><Activity size={20} /></div>
            <div className="kpi-info">
              <label>System Utilization</label>
              <div className="kpi-value-wrap">
                <span className="value">84.2%</span>
                <span className="trend positive">+2.4%</span>
              </div>
            </div>
          </div>
          <div className="kpi-card-modern neon-purple">
            <div className="kpi-icon"><Video size={20} /></div>
            <div className="kpi-info">
              <label>TeleLink Saturation</label>
              <div className="kpi-value-wrap">
                <span className="value">62/h</span>
                <span className="trend positive">+18%</span>
              </div>
            </div>
          </div>
          <div className="kpi-card-modern neon-green">
            <div className="kpi-icon"><Users size={20} /></div>
            <div className="kpi-info">
              <label>Total Intake (v24)</label>
              <div className="kpi-value-wrap">
                <span className="value">342</span>
                <span className="trend neutral">STABLE</span>
              </div>
            </div>
          </div>
          <div className="kpi-card-modern neon-amber">
            <div className="kpi-icon"><Clock size={20} /></div>
            <div className="kpi-info">
              <label>P-ETA Variance</label>
              <div className="kpi-value-wrap">
                <span className="value">-1.2m</span>
                <span className="trend positive">IMPROVED</span>
              </div>
            </div>
          </div>
        </div>

        {/* Row 2: Main Traffic & Triage */}
        <div className="analytics-body-layout">
          <div className="intel-card large">
            <div className="card-top">
              <div className="card-title">
                <TrendingUp size={16} />
                <span>Patient Inflow / Capacity Overlap</span>
              </div>
              <div className="legend-mini">
                <span className="dot current" /> Live Intake
                <span className="dot base" /> Expected
              </div>
            </div>
            <div className="viewport-chart">
               <ResponsiveContainer width="100%" height={320}>
                 <AreaChart data={volumeData}>
                   <defs>
                     <linearGradient id="colorIntake" x1="0" y1="0" x2="0" y2="1">
                       <stop offset="5%" stopColor="var(--accent-cyan)" stopOpacity={0.1}/>
                       <stop offset="95%" stopColor="var(--accent-cyan)" stopOpacity={0}/>
                     </linearGradient>
                   </defs>
                   <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsla(215, 32%, 17%, 0.05)" />
                   <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fontSize: 10, fontWeight: 750, fill: 'var(--text-muted)' }} />
                   <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 10, fontWeight: 750, fill: 'var(--text-muted)' }} />
                   <Tooltip 
                     contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: 'var(--shadow-premium)', background: '#fff' }}
                   />
                   <Area type="monotone" dataKey="count" stroke="var(--accent-cyan)" strokeWidth={3} fillOpacity={1} fill="url(#colorIntake)" />
                   <Line type="monotone" dataKey="baseline" stroke="var(--text-muted)" strokeDasharray="5 5" strokeWidth={1} dot={false} />
                 </AreaChart>
               </ResponsiveContainer>
            </div>
          </div>

          <div className="intel-card side">
            <div className="card-top">
              <div className="card-title">
                <PieChart size={16} />
                <span>Urgency Index</span>
              </div>
            </div>
            <div className="viewport-chart donut">
               <ResponsiveContainer width="100%" height={240}>
                 <RePieChart>
                   <Pie
                     data={triageData}
                     innerRadius={65}
                     outerRadius={85}
                     paddingAngle={8}
                     dataKey="value"
                   >
                     {triageData.map((e, idx) => <Cell key={idx} fill={e.color} stroke="none" />)}
                   </Pie>
                   <Tooltip />
                 </RePieChart>
               </ResponsiveContainer>
               <div className="donut-center-label">
                  <span className="v">126</span>
                  <span className="l">TOTAL</span>
               </div>
            </div>
            <div className="pie-legend-v2">
               {triageData.map(t => (
                 <div key={t.name} className="legend-row">
                    <div className="l-side">
                      <div className="l-dot" style={{ background: t.color }} />
                      <span className="l-name">{t.name.split(' ')[0]}</span>
                    </div>
                    <span className="l-val">{t.value}%</span>
                 </div>
               ))}
            </div>
          </div>
        </div>

        {/* Row 3: Dept Load & Alerts */}
        <div className="intelligence-footer-grid">
           <div className="intel-card medium no-bg">
              <div className="card-title small">DEPARTMENTAL LOAD (HEATMAP)</div>
              <div className="dept-load-stack">
                 {departmentEfficiency.map(d => (
                   <div key={d.dept} className="dept-progress-block">
                      <div className="d-info">
                        <span className="d-name">{d.dept}</span>
                        <span className="d-val">{d.load}% Load</span>
                      </div>
                      <div className="d-bar-bg">
                         <div className="d-bar-fill" style={{ width: `${d.load}%`, background: d.load > 85 ? 'var(--alert-red)' : 'var(--accent-cyan)' }} />
                      </div>
                   </div>
                 ))}
              </div>
           </div>

           <div className="intel-card medium glass-alert">
              <div className="card-title small alert-mode"><Activity size={14} /> LIVE ANOMALY DETECTION</div>
              <div className="anomaly-list">
                 <div className="anomaly-item">
                    <span className="time">14:02</span>
                    <p>Suboptimal triage time detected in ER South Cluster.</p>
                 </div>
                 <div className="anomaly-item warning">
                    <span className="time">13:45</span>
                    <p>TeleLink latency spike (+45ms) reported in Hub 4.</p>
                 </div>
              </div>
           </div>
        </div>
      </div>
    </motion.div>
  );
};
