import React, { useState, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Search,
  Activity,
  Wind,
  Video,
  Zap,
  ShieldAlert,
  Database,
  Radio,
  Clock,
  ChevronRight,
  TrendingUp,
  Filter,
  AlertCircle,
  Truck,
  CheckCircle2,
  X,
  LayoutDashboard
} from 'lucide-react';
import { hospitalApi } from '../../api/hospital';
import { 
  ResponsiveContainer, 
  PieChart, 
  Pie, 
  Cell, 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  Tooltip,
  AreaChart,
  Area
} from 'recharts';

interface EDMonitorProps {
  incomingPatients: any[];
  selectedHospital: any;
  departments: any[];
  onRefresh?: () => void;
  onOpenBooking: () => void;
  onOpenTelelink: () => void;
}

export const EDMonitor: React.FC<EDMonitorProps> = ({
  incomingPatients,
  selectedHospital,
  departments,
  onRefresh,
  onOpenBooking,
  onOpenTelelink,
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('ALL');
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [assigningPatientId, setAssigningPatientId] = useState<string | null>(null);
  const [isAdmitting, setIsAdmitting] = useState(false);

  const toggleExpand = (id: string) => {
    setExpandedId(expandedId === id ? null : id);
  };

  const handleAdmit = async (patientId: string, departmentId: string) => {
    setIsAdmitting(true);
    try {
      const patient = incomingPatients.find(p => p.id === patientId);
      const realId = patient?.originalId || patientId;
      
      const token = localStorage.getItem('teleems_token') || '';
      const res = await hospitalApi.admitPatient(realId, departmentId, token);
      if (res.status === 200 || res.status === 201) {
        setAssigningPatientId(null);
        if (onRefresh) onRefresh();
      } else {
        alert('Admission failed: ' + (res.message || 'Unknown error'));
      }
    } catch (err: any) {
      alert('Error admitting patient: ' + err.message);
    } finally {
      setIsAdmitting(false);
    }
  };

  const stats = useMemo(() => {
    return {
      total: incomingPatients.filter(p => p.status === 'IN_TRANSIT').length,
      critical: incomingPatients.filter(p => (p.triage === 'RED' || p.triage === 'CRITICAL') && p.status !== 'HANDOFF_COMPLETE').length,
      onsite: incomingPatients.filter(p => p.status === 'ARRIVED').length,
      handoff: incomingPatients.filter(p => p.status === 'HANDOFF_COMPLETE').length,
    };
  }, [incomingPatients]);

  const filteredPatients = useMemo(() => {
    return incomingPatients.filter(patient => {
      const matchesSearch = 
        patient.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        patient.mrn.toLowerCase().includes(searchQuery.toLowerCase()) ||
        patient.ambulanceId.toLowerCase().includes(searchQuery.toLowerCase()) ||
        patient.complaint.toLowerCase().includes(searchQuery.toLowerCase());
      
      const matchesStatus = statusFilter === 'ALL' || patient.status === statusFilter;
      
      return matchesSearch && matchesStatus;
    });
  }, [incomingPatients, searchQuery, statusFilter]);

  const statuses = ['ALL', 'IN_TRANSIT', 'ARRIVED', 'HANDOFF_COMPLETE'];

  const triageData = useMemo(() => {
    const counts: any = { RED: 0, ORANGE: 0, YELLOW: 0, GREEN: 0, WHITE: 0 };
    incomingPatients.forEach(p => {
      const t = String(p.triage).toUpperCase();
      if (counts[t] !== undefined) counts[t]++;
      else counts.GREEN++; // fallback
    });
    return [
      { name: 'Critical', value: counts.RED, color: '#ef4444' },
      { name: 'Urgent', value: counts.ORANGE, color: '#f97316' },
      { name: 'Stable', value: counts.YELLOW, color: '#eab308' },
      { name: 'Minimal', value: counts.GREEN, color: '#22c55e' },
      { name: 'Routine', value: counts.WHITE, color: '#94a3b8' },
    ].filter(d => d.value > 0);
  }, [incomingPatients]);

  const loadData = useMemo(() => {
    return [
      { time: '08:00', load: Math.max(0, stats.total - 2) },
      { time: '10:00', load: Math.max(0, stats.total - 1) },
      { time: '12:00', load: stats.total + 1 },
      { time: 'NOW', load: stats.total },
    ];
  }, [stats.total]);

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      className="module-content ed-monitor-tactical"
      style={{ background: 'var(--tactical-bg)', minHeight: '100%', padding: '24px' }}
    >
      {/* Metrics Row */}
      <div className="metrics-row-modern">
        {[
          { label: 'Incoming', count: stats.total, icon: <Activity size={20} />, color: '#0ea5e9' },
          { label: 'Critical', count: stats.critical, icon: <AlertCircle size={20} />, color: '#ef4444' },
          { label: 'On-Site', count: stats.onsite, icon: <Truck size={20} />, color: '#f59e0b' },
          { label: 'Completed', count: stats.handoff, icon: <CheckCircle2 size={20} />, color: '#10b981' },
        ].map((m, i) => (
          <div key={i} className="metric-card-premium">
            <div className="metric-icon-wrap" style={{ color: m.color }}>
              {m.icon}
            </div>
            <div>
              <div style={{ fontSize: '1.5rem', fontWeight: 800, color: '#0f172a', lineHeight: 1 }}>{m.count}</div>
              <div style={{ fontSize: '0.7rem', fontWeight: 700, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.05em', marginTop: '4px' }}>{m.label}</div>
            </div>
          </div>
        ))}
      </div>

      <div className="tactical-board-container">
        <div className="board-header-tactical" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '32px' }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '10px', color: '#ef4444', fontWeight: 700, fontSize: '0.75rem', letterSpacing: '0.05em' }}>
              <Radio size={14} /> LIVE TRIAGE DATA STREAM
            </div>
            <h2 style={{ margin: '8px 0 0 0', fontSize: '1.5rem', fontWeight: 700, color: '#1e293b', letterSpacing: '-0.02em' }}>Emergent Intake Board</h2>
          </div>
          
          <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
            <div className="search-mini" style={{ width: '300px', background: '#f1f5f9', border: '1px solid #e2e8f0' }}>
              <Search size={16} color="#64748b" />
              <input 
                type="text" 
                placeholder="Filter by Name, MRN, Unit..." 
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                style={{ fontWeight: 600 }}
              />
            </div>
            
            <div className="setup-nav" style={{ background: '#f1f5f9', padding: '4px', borderRadius: '12px' }}>
              {statuses.map(status => (
                <button
                  key={status}
                  className={`setup-nav-item ${statusFilter === status ? 'active' : ''}`}
                  onClick={() => setStatusFilter(status)}
                  style={{ fontSize: '0.7rem', fontWeight: 700, padding: '6px 14px' }}
                >
                  {status.replace('_', ' ')}
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="ed-grid-modern">
          <div className="triage-feed-container">
            <AnimatePresence mode="popLayout">
              {filteredPatients.length > 0 ? (
                filteredPatients.map((patient) => (
                  <motion.div
                    key={patient.id}
                    layout
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, scale: 0.95 }}
                    className="tactical-patient-card"
                  >
                    <div className={`card-status-indicator ${patient.triage}`} />
                    
                    <div className="card-main-tactical">
                      {/* Unit & ETA */}
                      <div className="unit-info-hex">
                        <div className="unit-label-premium">UNIT: {patient.ambulanceId}</div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '8px' }}>
                          <div style={{ width: 10, height: 10, background: patient.triage === 'RED' ? '#ef4444' : '#22c55e', borderRadius: '50%' }} />
                          <span style={{ fontSize: '0.9rem', fontWeight: 700, color: '#1e293b' }}>ETA {patient.eta}</span>
                        </div>
                        <div style={{ fontSize: '0.7rem', color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.02em' }}>{patient.status.replace('_', ' ')}</div>
                      </div>

                      {/* Identity & Complaint */}
                      <div className="p-identity-block">
                        <div className="p-name-premium">{patient.name}</div>
                        <div className="p-meta-inline">
                          <span style={{ color: 'var(--accent-cyan)', background: 'rgba(14, 165, 233, 0.08)', padding: '2px 8px', borderRadius: '6px', fontSize: '0.7rem' }}>{patient.mrn}</span>
                          <span>•</span>
                          <span>{patient.age}Y</span>
                          <span>•</span>
                          <span>{patient.gender}</span>
                        </div>
                        <div style={{ marginTop: '10px' }}>
                           <div className={`complaint-badge-tactical ${patient.triage === 'RED' ? 'CRITICAL' : ''}`}>
                             <TrendingUp size={14} />
                             {patient.complaint}
                           </div>
                        </div>
                      </div>

                      {/* Vitals Monitor */}
                      <div className="vitals-monitor-block">
                        <div className="v-node-tactical hr">
                          <span className="v-val">{patient.vitals.hr}</span>
                          <span className="v-lbl">HR</span>
                        </div>
                        <div style={{ width: '1px', height: '30px', background: 'rgba(255,255,255,0.08)' }} />
                        <div className="v-node-tactical spo2">
                          <span className="v-val">{patient.vitals.spo2}</span>
                          <span className="v-lbl">SPO2</span>
                        </div>
                        <div style={{ width: '1px', height: '30px', background: 'rgba(255,255,255,0.08)' }} />
                        <div className="v-node-tactical bp">
                          <span className="v-val">{patient.vitals.bp}</span>
                          <span className="v-lbl">BP</span>
                        </div>
                      </div>

                      {/* Actions */}
                      <div className="tactical-actions">
                        <div style={{ display: 'flex', gap: '8px' }}>
                           <button className="action-btn-tactical primary" onClick={onOpenTelelink} style={{ flex: 1 }}>
                             <Video size={14} /> JOIN
                           </button>
                           <button 
                             className="action-btn-tactical" 
                             onClick={() => toggleExpand(patient.id)}
                             style={{ flex: 1 }}
                           >
                             VIEW DATA
                           </button>
                        </div>
                        <div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
                           <button className="action-btn-tactical" onClick={() => setAssigningPatientId(patient.id)} style={{ flex: 1, background: '#f8fafc', color: 'var(--accent-cyan)', border: '1px solid var(--accent-cyan-soft)' }}>
                             <LayoutDashboard size={14} /> ASSIGN
                           </button>
                           {/* <button className="action-btn-tactical" onClick={onOpenBooking} style={{ flex: 1 }}>
                             TRIAGE REG.
                           </button> */}
                        </div>
                      </div>
                    </div>
                  </motion.div>
                ))
              ) : (
                <div style={{ padding: '100px 40px', textAlign: 'center', background: '#f8fafc', borderRadius: '32px', border: '2px dashed #e2e8f0' }}>
                  <div style={{ width: 80, height: 80, borderRadius: '50%', background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 24px auto', boxShadow: '0 10px 25px rgba(0,0,0,0.05)' }}>
                    <Filter size={32} color="#94a3b8" />
                  </div>
                  <h3 style={{ color: '#1e293b', margin: '0 0 8px 0', fontWeight: 800 }}>Board Stabilized</h3>
                  <p style={{ color: '#64748b', fontSize: '0.9rem', maxWidth: '300px', margin: '8px auto 0 auto' }}>All dispatches accounted for. No incoming units match current filters.</p>
                </div>
              )}
            </AnimatePresence>
          </div>

          <div className="ed-intel-sidebar" style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
             <div className="hub-card premium-ops" style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: '24px', padding: '24px' }}>
                <div style={{ fontSize: '0.65rem', fontWeight: 900, color: '#64748b', letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: '20px' }}>Triage Distribution</div>
                <div style={{ height: '180px', width: '100%' }}>
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={triageData}
                        innerRadius={55}
                        outerRadius={75}
                        paddingAngle={5}
                        dataKey="value"
                      >
                        {triageData.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={entry.color} />
                        ))}
                      </Pie>
                      <Tooltip 
                        contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 12px rgba(0,0,0,0.1)' }}
                        itemStyle={{ fontSize: '12px', fontWeight: 600 }}
                      />
                    </PieChart>
                  </ResponsiveContainer>
                  <div style={{ display: 'flex', justifyContent: 'center', gap: '12px', marginTop: '10px', flexWrap: 'wrap' }}>
                    {triageData.map((d, i) => (
                      <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                        <div style={{ width: 8, height: 8, borderRadius: '50%', background: d.color }} />
                        <span style={{ fontSize: '0.65rem', fontWeight: 700, color: '#64748b' }}>{d.name}</span>
                      </div>
                    ))}
                  </div>
                </div>
             </div>

             <div className="hub-card premium-ops" style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: '24px', padding: '24px' }}>
                <div style={{ fontSize: '0.65rem', fontWeight: 900, color: '#64748b', letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: '20px' }}>Inflow Velocity</div>
                <div style={{ height: '120px', width: '100%' }}>
                  <ResponsiveContainer width="100%" height="100%">
                    <AreaChart data={loadData}>
                      <defs>
                        <linearGradient id="colorLoad" x1="0" y1="0" x2="0" y2="1">
                          <stop offset="5%" stopColor="#0ea5e9" stopOpacity={0.3}/>
                          <stop offset="95%" stopColor="#0ea5e9" stopOpacity={0}/>
                        </linearGradient>
                      </defs>
                      <Tooltip 
                         contentStyle={{ borderRadius: '10px', border: 'none', boxShadow: '0 2px 8px rgba(0,0,0,0.05)' }}
                         labelStyle={{ fontSize: '10px', color: '#94a3b8' }}
                      />
                      <Area type="monotone" dataKey="load" stroke="#0ea5e9" fillOpacity={1} fill="url(#colorLoad)" strokeWidth={3} />
                    </AreaChart>
                  </ResponsiveContainer>
                </div>
             </div>

             <div className="hub-card premium-ops" style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: '24px', padding: '24px' }}>
                <div style={{ fontSize: '0.65rem', fontWeight: 900, color: '#ef4444', letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: '20px' }}>System Alerts</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                   <button className="code-btn-modern red" style={{ height: '60px' }}>
                      <div className="c-info">
                         <strong style={{ fontSize: '1rem' }}>CODE RED</strong>
                         <span>STAT Response Required</span>
                      </div>
                      <Zap size={20} fill="#fff" />
                   </button>
                   <button className="code-btn-modern trauma" style={{ height: '60px', background: 'linear-gradient(135deg, #f59e0b, #d97706)' }}>
                      <div className="c-info">
                         <strong style={{ fontSize: '1rem' }}>TRAUMA STAT</strong>
                         <span>Activation Sequence</span>
                      </div>
                      <ShieldAlert size={20} fill="#fff" />
                   </button>
                </div>
             </div>
          </div>
        </div>
      </div>

      {createPortal(
        <AnimatePresence>
          {expandedId && (
            <div style={{ position: 'fixed', inset: 0, zIndex: 10000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                onClick={() => setExpandedId(null)}
                style={{ position: 'absolute', inset: 0, background: 'rgba(15, 23, 42, 0.8)', backdropFilter: 'blur(4px)' }}
              />
              <motion.div
                initial={{ opacity: 0, scale: 0.9, y: 20 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.9, y: 20 }}
                style={{ 
                  position: 'relative', 
                  background: '#fff', 
                  borderRadius: '24px', 
                  width: '100%', 
                  maxWidth: '1000px', 
                  maxHeight: '90vh', 
                  overflow: 'hidden',
                  boxShadow: '0 25px 50px -12px rgba(0,0,0,0.5)'
                }}
              >
                {(() => {
                  const patient = incomingPatients.find(p => p.id === expandedId);
                  if (!patient) return null;
                  return (
                    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
                      {/* Modal Header */}
                      <div style={{ padding: '24px', borderBottom: '1px solid #f1f5f9', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: '#f8fafc' }}>
                         <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
                            <div className={`card-status-indicator ${patient.triage}`} style={{ width: '4px', height: '40px', borderRadius: '4px' }} />
                            <div>
                               <h3 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 800, color: '#1e293b' }}>{patient.name} <span style={{ color: '#94a3b8', fontWeight: 500, fontSize: '1rem' }}>• {patient.mrn}</span></h3>
                               <div style={{ fontSize: '0.85rem', color: '#64748b', marginTop: '4px' }}>
                                  {patient.age}Y • {patient.gender} • Unit {patient.ambulanceId} • Status: {patient.status.replace('_', ' ')}
                               </div>
                            </div>
                         </div>
                         <button 
                           onClick={() => setExpandedId(null)}
                           style={{ width: '40px', height: '40px', borderRadius: '12px', border: '1px solid #e2e8f0', background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}
                         >
                           <X size={20} color="#64748b" />
                         </button>
                      </div>

                      {/* Modal Body */}
                      <div style={{ padding: '32px', overflowY: 'auto' }}>
                         <div className="detail-module-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '32px' }}>
                            {/* Clinical Module */}
                            <div className="detail-module">
                               <h5 style={{ fontSize: '0.7rem', color: '#94a3b8', textTransform: 'uppercase', marginBottom: '16px', letterSpacing: '0.1em', fontWeight: 800 }}>Clinical Assessment</h5>
                               <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
                                  <div style={{ background: '#f8fafc', padding: '16px', borderRadius: '12px', border: '1px solid #e2e8f0' }}>
                                     <div style={{ fontSize: '0.65rem', color: '#64748b', marginBottom: '6px' }}>GCS TOTAL</div>
                                     <div style={{ fontSize: '1.5rem', fontWeight: 900, color: '#1e293b' }}>{patient.gcs?.total || '--'}</div>
                                     <div style={{ fontSize: '0.65rem', color: '#94a3b8', marginTop: '4px' }}>E:{patient.gcs?.eye} V:{patient.gcs?.verbal} M:{patient.gcs?.motor}</div>
                                  </div>
                                  <div style={{ background: '#f8fafc', padding: '16px', borderRadius: '12px', border: '1px solid #e2e8f0' }}>
                                     <div style={{ fontSize: '0.65rem', color: '#64748b', marginBottom: '6px' }}>AVPU</div>
                                     <div style={{ fontSize: '1.5rem', fontWeight: 900, color: '#1e293b' }}>{patient.avpu}</div>
                                  </div>
                                  <div style={{ background: '#f8fafc', padding: '16px', borderRadius: '12px', border: '1px solid #e2e8f0', gridColumn: 'span 2' }}>
                                     <div style={{ fontSize: '0.65rem', color: '#64748b', marginBottom: '8px' }}>PUPILS</div>
                                     <div style={{ display: 'flex', gap: '30px' }}>
                                        <div style={{ fontSize: '1rem', fontWeight: 700 }}><span style={{ color: '#94a3b8' }}>LEFT:</span> {patient.pupils?.left || '--'}</div>
                                        <div style={{ fontSize: '1rem', fontWeight: 700 }}><span style={{ color: '#94a3b8' }}>RIGHT:</span> {patient.pupils?.right || '--'}</div>
                                     </div>
                                  </div>
                               </div>
                            </div>

                            {/* HPI Module */}
                            <div className="detail-module">
                               <h5 style={{ fontSize: '0.7rem', color: '#94a3b8', textTransform: 'uppercase', marginBottom: '16px', letterSpacing: '0.1em', fontWeight: 800 }}>History of Illness (HPI)</h5>
                               <div style={{ background: '#fff', padding: '20px', borderRadius: '16px', border: '1px solid #e2e8f0', boxShadow: '0 4px 6px -1px rgba(0,0,0,0.05)' }}>
                                  <div style={{ marginBottom: '16px' }}>
                                     <div style={{ fontSize: '0.7rem', color: '#94a3b8' }}>CHIEF COMPLAINT</div>
                                     <div style={{ fontSize: '1.1rem', fontWeight: 800, color: '#1e293b' }}>{patient.complaint}</div>
                                  </div>
                                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
                                     <div>
                                        <div style={{ fontSize: '0.65rem', color: '#94a3b8' }}>ONSET</div>
                                        <div style={{ fontSize: '0.85rem', fontWeight: 700 }}>{patient.hpi?.onset || '--'}</div>
                                     </div>
                                     <div>
                                        <div style={{ fontSize: '0.65rem', color: '#94a3b8' }}>DURATION</div>
                                        <div style={{ fontSize: '0.85rem', fontWeight: 700 }}>{patient.hpi?.duration || '--'}m</div>
                                     </div>
                                     <div>
                                        <div style={{ fontSize: '0.65rem', color: '#94a3b8' }}>SEVERITY</div>
                                        <div style={{ fontSize: '0.85rem', fontWeight: 700 }}>{patient.hpi?.severity || '--'}/10</div>
                                     </div>
                                     <div>
                                        <div style={{ fontSize: '0.65rem', color: '#94a3b8' }}>CHARACTER</div>
                                        <div style={{ fontSize: '0.85rem', fontWeight: 700 }}>{patient.hpi?.character || '--'}</div>
                                     </div>
                                  </div>
                               </div>
                            </div>

                            {/* Medical Background */}
                            <div className="detail-module">
                               <h5 style={{ fontSize: '0.7rem', color: '#94a3b8', textTransform: 'uppercase', marginBottom: '16px', letterSpacing: '0.1em', fontWeight: 800 }}>Medical Records</h5>
                               <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                                  {[
                                     { label: 'ALLERGIES', val: patient.allergies.map((a: any) => a.name).join(', '), color: '#fee2e2', textColor: '#b91c1c' },
                                     { label: 'MEDICATIONS', val: patient.medications.join(', '), color: '#f1f5f9', textColor: '#475569' },
                                     { label: 'CONDITIONS', val: patient.conditions.join(', '), color: '#f1f5f9', textColor: '#475569' },
                                     { label: 'SURGERIES', val: patient.surgeries.join(', '), color: '#f1f5f9', textColor: '#475569' },
                                  ].map((item, idx) => (
                                     <div key={idx} style={{ background: item.val ? item.color : 'transparent', padding: '12px 16px', borderRadius: '10px', border: item.val ? 'none' : '1px dashed #e2e8f0' }}>
                                        <div style={{ fontSize: '0.6rem', color: '#64748b', fontWeight: 800, marginBottom: '4px' }}>{item.label}</div>
                                        <div style={{ fontSize: '0.9rem', color: item.textColor, fontWeight: 700 }}>{item.val || '--'}</div>
                                     </div>
                                  ))}
                               </div>
                            </div>

                            {/* Footer Info Row */}
                            <div style={{ gridColumn: '1 / -1', borderTop: '1px solid #f1f5f9', paddingTop: '32px', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(350px, 1fr))', gap: '24px' }}>
                               <div style={{ background: '#f8fafc', padding: '20px', borderRadius: '16px', border: '1px solid #e2e8f0' }}>
                                  <div style={{ fontSize: '0.7rem', color: '#94a3b8', marginBottom: '12px', fontWeight: 800 }}>INFORMER CONTACT</div>
                                  <div style={{ display: 'flex', gap: '40px' }}>
                                     <div><span style={{ fontSize: '0.65rem', color: '#94a3b8' }}>NAME:</span> <div style={{ fontSize: '0.9rem', fontWeight: 700 }}>{patient.informer?.name}</div></div>
                                     <div><span style={{ fontSize: '0.65rem', color: '#94a3b8' }}>RELATION:</span> <div style={{ fontSize: '0.9rem', fontWeight: 700 }}>{patient.informer?.relation}</div></div>
                                     <div><span style={{ fontSize: '0.65rem', color: '#94a3b8' }}>PHONE:</span> <div style={{ fontSize: '0.9rem', fontWeight: 700 }}>{patient.informer?.phone}</div></div>
                                  </div>
                               </div>
                               <div style={{ background: patient.mlc?.is_mlc ? '#fffef2' : '#f8fafc', padding: '20px', borderRadius: '16px', border: `1px solid ${patient.mlc?.is_mlc ? '#fef08a' : '#e2e8f0'}` }}>
                                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
                                     <div style={{ fontSize: '0.7rem', color: '#94a3b8', fontWeight: 800 }}>MLC RECORD</div>
                                     {patient.mlc?.is_mlc && <span style={{ background: '#fef9c3', color: '#854d0e', fontSize: '0.6rem', fontWeight: 900, padding: '4px 8px', borderRadius: '6px' }}>LEGAL CLEARANCE REQ.</span>}
                                  </div>
                                  <div style={{ display: 'flex', gap: '40px' }}>
                                     <div><span style={{ fontSize: '0.65rem', color: '#94a3b8' }}>FIR:</span> <div style={{ fontSize: '0.9rem', fontWeight: 700 }}>{patient.mlc?.fir || '--'}</div></div>
                                     <div><span style={{ fontSize: '0.65rem', color: '#94a3b8' }}>STATION:</span> <div style={{ fontSize: '0.9rem', fontWeight: 700 }}>{patient.mlc?.station || '--'}</div></div>
                                     <div><span style={{ fontSize: '0.65rem', color: '#94a3b8' }}>OFFICER:</span> <div style={{ fontSize: '0.9rem', fontWeight: 700 }}>{patient.mlc?.officer || '--'}</div></div>
                                  </div>
                               </div>
                            </div>
                         </div>
                      </div>
                      
                      {/* Modal Actions */}
                      <div style={{ padding: '24px', borderTop: '1px solid #f1f5f9', background: '#f8fafc', display: 'flex', justifyContent: 'flex-end', gap: '16px' }}>
                          <button className="action-btn-tactical" onClick={() => setExpandedId(null)} style={{ padding: '0 24px', height: '44px' }}>CLOSE REPORT</button>
                          <button className="action-btn-tactical primary" onClick={onOpenTelelink} style={{ padding: '0 32px', height: '44px' }}><Video size={18} /> INITIATE CALL</button>
                      </div>
                    </div>
                  );
                })()}
              </motion.div>
            </div>
          )}
        </AnimatePresence>,
        document.body
      )}

      {/* Assignment Modal */}
      {createPortal(
        <AnimatePresence>
          {assigningPatientId && (
            <div style={{ position: 'fixed', inset: 0, zIndex: 10001, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                onClick={() => setAssigningPatientId(null)}
                style={{ position: 'absolute', inset: 0, background: 'rgba(15, 23, 42, 0.4)', backdropFilter: 'blur(2px)' }}
              />
              <motion.div
                initial={{ opacity: 0, scale: 0.95, y: 10 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.95, y: 10 }}
                style={{ 
                  position: 'relative', 
                  background: '#fff', 
                  borderRadius: '20px', 
                  width: '100%', 
                  maxWidth: '450px', 
                  overflow: 'hidden',
                  boxShadow: '0 20px 40px rgba(0,0,0,0.2)'
                }}
              >
                <div style={{ padding: '20px 24px', borderBottom: '1px solid #f1f5f9', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: '#f8fafc' }}>
                   <h3 style={{ margin: 0, fontSize: '1.1rem', fontWeight: 800, color: '#1e293b' }}>Assign Department</h3>
                   <button 
                     onClick={() => setAssigningPatientId(null)}
                     style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: '#94a3b8' }}
                   >
                     <X size={20} />
                   </button>
                </div>
                
                <div style={{ padding: '24px', maxHeight: '400px', overflowY: 'auto' }}>
                  <div style={{ marginBottom: '16px', fontSize: '0.85rem', color: '#64748b' }}>
                    Select target clinical unit for: <strong>{incomingPatients.find(p => p.id === assigningPatientId)?.name}</strong>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                    {departments.length > 0 ? departments.map(dept => (
                      <button
                        key={dept.id}
                        disabled={isAdmitting}
                        onClick={() => handleAdmit(assigningPatientId, dept.id)}
                        style={{
                          width: '100%',
                          padding: '14px 18px',
                          borderRadius: '12px',
                          border: '1px solid #e2e8f0',
                          background: '#fff',
                          textAlign: 'left',
                          cursor: isAdmitting ? 'not-allowed' : 'pointer',
                          transition: 'all 0.2s',
                          display: 'flex',
                          justifyContent: 'space-between',
                          alignItems: 'center'
                        }}
                        onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--accent-cyan)'}
                        onMouseLeave={(e) => e.currentTarget.style.borderColor = '#e2e8f0'}
                      >
                        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                          <div style={{ width: 8, height: 8, borderRadius: '50%', background: dept.isActive ? '#10b981' : '#cbd5e1' }} />
                          <div>
                            <div style={{ fontSize: '0.9rem', fontWeight: 700, color: '#1e293b' }}>{dept.name}</div>
                            <div style={{ fontSize: '0.7rem', color: '#94a3b8' }}>Available: {dept.availableBeds} Units</div>
                          </div>
                        </div>
                        <ChevronRight size={16} color="#94a3b8" />
                      </button>
                    )) : (
                      <div style={{ textAlign: 'center', padding: '20px', color: '#94a3b8', fontSize: '0.9rem' }}>
                        No active departments found.
                      </div>
                    )}
                  </div>
                </div>

                {isAdmitting && (
                  <div style={{ position: 'absolute', inset: 0, background: 'rgba(255,255,255,0.7)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 10 }}>
                    <div className="spin" style={{ width: 24, height: 24, border: '2px solid #e2e8f0', borderTop: '2px solid var(--accent-cyan)', borderRadius: '50%' }} />
                  </div>
                )}
              </motion.div>
            </div>
          )}
        </AnimatePresence>,
        document.body
      )}
    </motion.div>
  );
};

