import { useState, useMemo, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  ArrowLeft, Pill, TestTube2, Calendar,
  AlertTriangle, ChevronDown, MapPin, Mail, Phone,
  Stethoscope, Activity, CheckCircle2, AlertCircle, FileText, Watch,
} from 'lucide-react';
import { format, isAfter, parseISO } from 'date-fns';
import { cn } from '../../utils/helpers';
import { usePractitionerStore, type PatientData } from '../store/usePractitionerStore';
import type { APIDiagnosis, APIHospitalVisit, APIPrescription, APITest } from '../../services/medical';

/* ── Helpers ───────────────────────────────────────────────────────────── */

function initials(name: string) {
  return name.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase();
}

function bmi(h?: number, w?: number) {
  if (!h || !w || h <= 0) return null;
  return w / ((h / 100) ** 2);
}

function bmiLabel(v: number) {
  if (v < 18.5) return 'Underweight';
  if (v < 25) return 'Normal';
  if (v < 30) return 'Overweight';
  return 'Obese';
}

function isActivePrescription(p: APIPrescription) {
  if (!p.endDate) return true;
  try { return isAfter(parseISO(p.endDate), new Date()); } catch { return false; }
}

function safeDate(d: string) { try { return parseISO(d); } catch { return new Date(d); } }
function fmt(d: string, f = 'MMM d, yyyy') { try { return format(safeDate(d), f); } catch { return d; } }
function medName(p: APIPrescription) { return p.medication?.brandName || p.medication?.genericName || p.prescriptionId || 'Unknown'; }
function dxName(d: APIDiagnosis) { return d.disease?.name || d.icdCode; }

function subStatusStyle(status: string) {
  switch (status?.toLowerCase()) {
    case 'normal':              return { dot: 'bg-emerald-500', cls: 'text-emerald-600 bg-emerald-100' };
    case 'high': case 'abnormal': return { dot: 'bg-red-500',    cls: 'text-red-600 bg-red-100' };
    case 'low':                 return { dot: 'bg-amber-500',  cls: 'text-amber-600 bg-amber-100' };
    default:                    return { dot: 'bg-gray-400',   cls: 'text-gray-600 bg-gray-100' };
  }
}

function abnormalCount(tests: APITest[]) {
  let n = 0;
  for (const t of tests) for (const s of t.subtests) {
    const st = s.status?.toLowerCase();
    if (st === 'abnormal' || st === 'high' || st === 'low') n++;
  }
  return n;
}

/* ── Empty State ───────────────────────────────────────────────────────── */

function EmptyState({ icon: Icon, title, sub }: { icon: React.ComponentType<{ className?: string }>; title: string; sub: string }) {
  return (
    <div className="bg-gray-50 rounded-xl border border-gray-200 border-dashed p-12 text-center">
      <div className="w-12 h-12 rounded-full bg-white shadow-sm flex items-center justify-center mx-auto mb-3">
        <Icon className="h-5 w-5 text-gray-400" />
      </div>
      <p className="text-sm font-medium text-gray-500">{title}</p>
      <p className="text-xs text-gray-400 mt-1">{sub}</p>
    </div>
  );
}

/* ── Profile Card ──────────────────────────────────────────────────────── */

function ProfileCard({ data, onViewPatientData }: { data: PatientData; onViewPatientData: () => void }) {
  const { user } = data;
  const bmiVal = bmi(user.height, user.weight);

  return (
    <div className="card p-6">
      <div className="flex items-start gap-5">
        {/* Avatar */}
        <div className="h-14 w-14 rounded-xl bg-primary/8 flex items-center justify-center shrink-0">
          <span className="text-primary text-lg font-semibold">{initials(user.dispName)}</span>
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between gap-4">
            <div>
              <h2 className="text-lg font-semibold text-gray-900 tracking-tight">{user.dispName}</h2>
              <div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-1.5 text-[13px] text-gray-500">
                {user.residentCity && (
                  <span className="flex items-center gap-1.5">
                    <MapPin className="h-3.5 w-3.5 text-gray-400" />
                    {user.residentCity}{user.residentCountry ? `, ${user.residentCountry}` : ''}
                  </span>
                )}
                {user.email && (
                  <span className="flex items-center gap-1.5">
                    <Mail className="h-3.5 w-3.5 text-gray-400" />
                    {user.email}
                  </span>
                )}
                {user.phoneNumber && (
                  <span className="flex items-center gap-1.5">
                    <Phone className="h-3.5 w-3.5 text-gray-400" />
                    {user.phoneNumber}
                  </span>
                )}
              </div>
            </div>
            <button onClick={onViewPatientData} className="btn-primary shrink-0">
              <Stethoscope className="h-4 w-4" />
              Start Consultation
            </button>
          </div>
        </div>
      </div>

      {/* Metrics strip */}
      <div className="grid grid-cols-4 mt-5 bg-gray-50/80 rounded-xl border border-gray-100 overflow-hidden divide-x divide-gray-100">
        {[
          { label: 'Weight', value: user.weight ? `${user.weight}` : '—', unit: user.weight ? 'kg' : undefined },
          { label: 'Height', value: user.height ? `${user.height}` : '—', unit: user.height ? 'cm' : undefined },
          { label: 'BMI', value: bmiVal ? bmiVal.toFixed(1) : '—', sub: bmiVal ? bmiLabel(bmiVal) : undefined },
          { label: 'Blood', value: user.bloodType || '—' },
        ].map(m => (
          <div key={m.label} className="py-3.5 px-4 text-center">
            <div className="flex items-baseline justify-center gap-1">
              <span className="text-xl font-semibold text-gray-900 tabular-nums">{m.value}</span>
              {m.unit && <span className="text-xs text-gray-400">{m.unit}</span>}
            </div>
            <p className="text-[11px] text-gray-400 font-medium uppercase tracking-wider mt-0.5">{m.label}</p>
            {m.sub && <p className="text-[11px] text-gray-500 mt-0.5">{m.sub}</p>}
          </div>
        ))}
      </div>

      {/* Allergies — inline in metrics strip style */}
      {user.allergies && user.allergies.length > 0 && (
        <div className="flex items-center gap-2 mt-3 text-[12px] text-gray-500">
          <span className="text-gray-400 font-medium">Allergies:</span>
          <span>{user.allergies.join(', ')}</span>
        </div>
      )}
    </div>
  );
}

/* ── Overview Tab ──────────────────────────────────────────────────────── */

function OverviewTab({ data }: { data: PatientData }) {
  const { diagnoses, prescriptions, tests } = data;
  const abn = abnormalCount(tests);

  const sortedDx = useMemo(
    () => [...diagnoses].sort((a, b) => safeDate(b.diagnosisDate).getTime() - safeDate(a.diagnosisDate).getTime()),
    [diagnoses],
  );

  const activeMeds = useMemo(
    () => prescriptions.filter(isActivePrescription),
    [prescriptions],
  );

  return (
    <div className="space-y-6">
      {abn > 0 && (
        <div className="card flex items-center gap-3 px-5 py-3.5">
          <div className="w-0.5 h-8 rounded-full bg-amber-400" />
          <AlertTriangle className="h-4 w-4 text-amber-500 shrink-0" />
          <span className="text-sm text-gray-700 font-medium">
            {abn} abnormal lab result{abn !== 1 ? 's' : ''} — review Lab Results tab
          </span>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Past Diagnoses */}
        <div className="card p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-gray-900 flex items-center gap-2">
              <Stethoscope className="h-4 w-4 text-primary" />
              Past Diagnoses
            </h3>
          </div>
          {sortedDx.length === 0 ? (
            <div className="py-8 text-center">
              <Activity className="h-5 w-5 text-gray-300 mx-auto mb-2" />
              <p className="text-sm text-gray-400">No diagnoses recorded</p>
            </div>
          ) : (
            <div className="relative border-l-2 border-gray-100/80 ml-2.5 space-y-5 pl-5 py-1">
              {sortedDx.map(d => {
                const dotColor = d.severity?.toLowerCase() === 'severe' ? 'border-red-400'
                  : d.severity?.toLowerCase() === 'moderate' ? 'border-amber-400'
                  : 'border-emerald-400';

                return (
                  <div key={d._id} className="relative group">
                    <div className={cn('absolute -left-[27px] top-1.5 w-3 h-3 rounded-full border-[2px] bg-white transition-colors', dotColor)} />

                    <div>
                      <div className="flex items-baseline gap-2 mb-0.5">
                        <span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wide">
                          {fmt(d.diagnosisDate, 'MMM d')}
                        </span>
                        {d.disease?.bodyRegion && (
                          <>
                            <span className="text-[10px] text-gray-300">&middot;</span>
                            <span className="text-[10px] text-gray-300 capitalize">{d.disease.bodyRegion}</span>
                          </>
                        )}
                      </div>

                      <h4 className="text-sm font-medium text-gray-800 mb-0.5 group-hover:text-blue-600 transition-colors">
                        {dxName(d)}
                      </h4>

                      <p className="text-xs text-gray-500">
                        {d.icdCode}{d.severity ? ` · ${d.severity}` : ''}
                      </p>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Active Medications */}
        <div className="card p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-gray-900">Current prescriptions</h3>
          </div>
          {activeMeds.length === 0 ? (
            <div className="py-8 text-center">
              <Pill className="h-5 w-5 text-gray-300 mx-auto mb-2" />
              <p className="text-sm text-gray-400">No active prescriptions</p>
            </div>
          ) : (
            <div className="space-y-0.5">
              {activeMeds.slice(0, 6).map(p => (
                <div key={p._id} className="flex items-center gap-3 px-3 py-2.5 -mx-1 rounded-lg hover:bg-gray-50/80 transition-colors group">
                  <div className="w-8 h-8 rounded-lg bg-blue-50 flex items-center justify-center shrink-0">
                    <Pill className="h-3.5 w-3.5 text-blue-600" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-[13px] font-medium text-gray-900">{medName(p)}</p>
                    <p className="text-[12px] text-gray-500 mt-0.5">
                      {[p.dosage, p.frequency].filter(Boolean).join(' · ')}
                    </p>
                  </div>
                  <span className="text-[11px] text-gray-400 shrink-0">
                    Started - {fmt(p.startDate, 'MMM d')}
                  </span>
                  <span className='text-[11px] text-gray-400 shrink-0'>
                    Until - {fmt(p.endDate, 'MMM d')}
                  </span>
                </div>
              ))}
              {activeMeds.length > 6 && (
                <p className="text-xs text-gray-400 text-center pt-2">
                  +{activeMeds.length - 6} more — see Prescriptions tab
                </p>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ── Medications Tab ───────────────────────────────────────────────────── */

function MedicationsTab({ prescriptions }: { prescriptions: APIPrescription[] }) {
  const sorted = useMemo(
    () => [...prescriptions].sort((a, b) => {
      const diff = (isActivePrescription(b) ? 1 : 0) - (isActivePrescription(a) ? 1 : 0);
      if (diff !== 0) return diff;
      return safeDate(b.startDate).getTime() - safeDate(a.startDate).getTime();
    }),
    [prescriptions],
  );

  if (prescriptions.length === 0) {
    return <EmptyState icon={Pill} title="No prescriptions" sub="Prescription records will appear here" />;
  }

  return (
    <div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
      <table className="w-full">
        <thead>
          <tr className="bg-gray-50 border-b border-gray-100">
            <th className="px-6 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Medication</th>
            <th className="px-6 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Dosage</th>
            <th className="px-6 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Frequency</th>
            <th className="px-6 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Period</th>
            <th className="px-6 py-3.5 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider">Status</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-100">
          {sorted.map(p => {
            const active = isActivePrescription(p);
            return (
              <tr key={p._id} className="hover:bg-gray-50/50 transition-colors">
                <td className="px-6 py-4">
                  <p className="text-[13px] font-medium text-gray-900">{medName(p)}</p>
                  {p.medication?.genericName && p.medication.brandName && (
                    <p className="text-[11px] text-gray-400 mt-0.5">{p.medication.genericName}</p>
                  )}
                </td>
                <td className="px-6 py-4 text-[13px] text-gray-700">{p.dosage || '—'}</td>
                <td className="px-6 py-4 text-[13px] text-gray-700">{p.frequency || '—'}</td>
                <td className="px-6 py-4 text-[13px] text-gray-500">
                  {fmt(p.startDate, 'MMM d, yy')}
                  {p.endDate && <span className="text-gray-400"> — {fmt(p.endDate, 'MMM d, yy')}</span>}
                </td>
                <td className="px-6 py-4 text-right">
                  <span className={cn(
                    'inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide',
                    active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
                  )}>
                    {active ? 'Active' : 'Expired'}
                  </span>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

/* ── Lab Results Tab ───────────────────────────────────────────────────── */

function LabResultsTab({ tests }: { tests: APITest[] }) {
  const [expanded, setExpanded] = useState<Set<string>>(new Set());
  const sorted = useMemo(
    () => [...tests].sort((a, b) => safeDate(b.date).getTime() - safeDate(a.date).getTime()),
    [tests],
  );

  const toggle = (id: string) => setExpanded(prev => {
    const next = new Set(prev);
    next.has(id) ? next.delete(id) : next.add(id);
    return next;
  });

  if (tests.length === 0) {
    return <EmptyState icon={TestTube2} title="No lab results" sub="Test results will appear here" />;
  }

  return (
    <div className="card p-0 overflow-hidden">
      <div className="divide-y divide-gray-100">
        {sorted.map(test => {
          const open = expanded.has(test._id);
          const abn = test.subtests.filter(s => {
            const st = s.status?.toLowerCase();
            return st === 'abnormal' || st === 'high' || st === 'low';
          }).length;

          return (
            <div key={test._id}>
              <button
                onClick={() => toggle(test._id)}
                className="w-full flex items-center gap-4 px-5 py-4 text-left hover:bg-gray-50/50 transition-colors group"
              >
                <div className="flex-1 min-w-0">
                  <p className="text-[13px] font-semibold text-gray-900">{test.name}</p>
                  <div className="flex items-center gap-1.5 mt-1 text-[12px] text-gray-500">
                    <span>{fmt(test.date)}</span>
                    <span className="text-gray-300">&middot;</span>
                    <span>{test.subtests.length} subtest{test.subtests.length !== 1 ? 's' : ''}</span>
                    {test.testType && (
                      <>
                        <span className="text-gray-300">&middot;</span>
                        <span>{test.testType}</span>
                      </>
                    )}
                  </div>
                </div>

                {abn > 0 ? (
                  <span className="text-[11px] text-red-600 font-medium flex items-center gap-1 shrink-0">
                    <AlertCircle className="h-3.5 w-3.5" />
                    {abn} abnormal
                  </span>
                ) : (
                  <span className="text-[11px] text-emerald-600 font-medium flex items-center gap-1 shrink-0">
                    <CheckCircle2 className="h-3.5 w-3.5" />
                    All normal
                  </span>
                )}

                <ChevronDown className={cn(
                  'h-4 w-4 text-gray-400 transition-transform duration-200 shrink-0',
                  open && 'rotate-180',
                )} />
              </button>

              {open && (
                <div className="border-t border-gray-100">
                  <table className="w-full">
                    <thead>
                      <tr className="bg-gray-50/80">
                        <th className="px-5 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Test</th>
                        <th className="px-5 py-3 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider">Value</th>
                        <th className="px-5 py-3 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider">Reference</th>
                        <th className="px-5 py-3 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                      {test.subtests.map((s, i) => {
                        const ss = subStatusStyle(s.status);
                        return (
                          <tr key={i} className="hover:bg-blue-50/30 transition-colors">
                            <td className="px-5 py-3.5">
                              <div className="flex items-center gap-2">
                                <span className={cn('h-1.5 w-1.5 rounded-full shrink-0', ss.dot)} />
                                <span className="text-[13px] text-gray-900">{s.name}</span>
                              </div>
                            </td>
                            <td className="px-5 py-3.5 text-right">
                              <span className="text-[13px] font-semibold text-gray-900">{s.value != null ? s.value : '—'}</span>
                              {s.unit && <span className="text-[11px] text-gray-400 ml-1">{s.unit}</span>}
                            </td>
                            <td className="px-5 py-3.5 text-right text-[12px] text-gray-400">
                              {s.refMin != null && s.refMax != null
                                ? `${s.refMin}–${s.refMax}`
                                : s.refMin != null ? `≥ ${s.refMin}`
                                : s.refMax != null ? `≤ ${s.refMax}`
                                : '—'}
                            </td>
                            <td className="px-5 py-3.5 text-right">
                              <span className={cn('inline-flex px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide capitalize', ss.cls)}>
                                {s.status || 'unknown'}
                              </span>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── Visits Tab ────────────────────────────────────────────────────────── */

function VisitsTab({ visits }: { visits: APIHospitalVisit[] }) {
  const sorted = useMemo(
    () => [...visits].sort((a, b) => safeDate(b.visitDate).getTime() - safeDate(a.visitDate).getTime()),
    [visits],
  );

  if (visits.length === 0) {
    return <EmptyState icon={Calendar} title="No visits" sub="Hospital visit records will appear here" />;
  }

  return (
    <div className="card p-6">
      <div className="relative border-l-2 border-gray-100/80 ml-2.5 space-y-6 pl-5 py-1">
        {sorted.map(v => {
          const primaryDx = v.populatedDiagnoses?.[0];
          const title = primaryDx?.diseaseName || v.department || 'General';
          const subtitle = [v.hospital, v.doctorName].filter(Boolean).join(' · ');

          return (
            <div key={v._id} className="relative group">
              <div className="absolute -left-[27px] top-1.5 w-3 h-3 rounded-full border-[2px] border-blue-400 bg-white group-hover:bg-blue-50 transition-colors" />

              <div>
                <div className="flex items-baseline gap-2 mb-0.5">
                  <span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wide">
                    {format(safeDate(v.visitDate), 'MMM d')}
                  </span>
                  <span className="text-[10px] text-gray-300">
                    {format(safeDate(v.visitDate), 'HH:mm')}
                  </span>
                </div>

                <h4 className="text-sm font-medium text-gray-800 mb-0.5 group-hover:text-blue-600 transition-colors">
                  {title}
                </h4>

                <p className="text-xs text-gray-500 leading-snug line-clamp-2">
                  {v.dischargeSummary
                    ? `${subtitle ? subtitle + '. ' : ''}${v.dischargeSummary}`
                    : subtitle || 'No details provided.'}
                </p>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── Notes Tab ─────────────────────────────────────────────────────────── */

function NotesTab({ patientId }: { patientId: string }) {
  const key = `hipograf_practitioner_notes_${patientId}`;
  const [notes, setNotes] = useState(() => localStorage.getItem(key) || '');
  const [saved, setSaved] = useState(true);

  useEffect(() => {
    setSaved(false);
    const t = setTimeout(() => { localStorage.setItem(key, notes); setSaved(true); }, 800);
    return () => clearTimeout(t);
  }, [notes, key]);

  return (
    <div className="card p-5">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-sm font-semibold text-gray-900">Clinical Notes</h3>
        <span className={cn('text-[12px] font-medium', saved ? 'text-emerald-600' : 'text-gray-400')}>
          {saved ? 'Saved' : 'Saving...'}
        </span>
      </div>
      <textarea
        value={notes}
        onChange={e => setNotes(e.target.value)}
        placeholder="Write your clinical notes about this patient..."
        className="w-full min-h-[200px] resize-y text-[13px] text-gray-700 bg-gray-50/50 border border-gray-200 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all placeholder:text-gray-400"
      />
      <p className="text-[11px] text-gray-400 text-right mt-2">
        Private · Stored locally · {notes.length} characters
      </p>
    </div>
  );
}

/* ── Tab: Wearables ────────────────────────────────────────────────────── */

function WearablesTab({ patientId }: { patientId: string }) {
  const [summary, setSummary] = useState<Record<string, { value: number; unit: string; date: string; provider: string }>>({});
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState('');

  useEffect(() => {
    const token = localStorage.getItem('hipograf_token');
    const base = import.meta.env.VITE_API_URL || '/api';
    fetch(`${base}/devices/patients/${patientId}/summary`, {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then(r => r.json())
      .then(data => {
        setSummary(data.summary || {});
        setMessage(data.message || '');
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, [patientId]);

  if (loading) return <p className="text-sm text-gray-400 py-8 text-center">Loading wearable data...</p>;

  const metrics = Object.entries(summary);
  if (metrics.length === 0) {
    return (
      <div className="card p-8 text-center">
        <Watch className="w-10 h-10 text-gray-300 mx-auto mb-3" />
        <p className="text-sm text-gray-500 mb-1">
          {message || "This patient hasn't shared device data, or hasn't connected any devices."}
        </p>
        <p className="text-xs text-gray-400">
          Supported: Samsung Health (via the Hipograf Companion app)
        </p>
      </div>
    );
  }

  return (
    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
      {metrics.map(([metric, data]) => (
        <div key={metric} className="card p-3">
          <p className="text-[11px] text-gray-400 capitalize mb-1">{metric.replace(/_/g, ' ')}</p>
          <p className="text-lg font-semibold text-gray-900">{typeof data.value === 'number' ? data.value.toLocaleString() : data.value}</p>
          <p className="text-[10px] text-gray-400 mt-0.5">{data.unit} · {data.date} · {data.provider}</p>
        </div>
      ))}
    </div>
  );
}

/* ── Main Page ─────────────────────────────────────────────────────────── */

export default function PatientDetailPage() {
  const { patientId } = useParams<{ patientId: string }>();
  const navigate = useNavigate();
  const { currentPatientData, currentPatientLoading, loadPatientDetail, enterPatientView } = usePractitionerStore();
  const [activeTab, setActiveTab] = useState('overview');

  useEffect(() => { if (patientId) loadPatientDetail(patientId); }, [patientId, loadPatientDetail]);

  if (currentPatientLoading) {
    return (
      <div className="flex items-center justify-center py-32">
        <div className="animate-spin h-6 w-6 border-2 border-primary border-t-transparent rounded-full" />
      </div>
    );
  }

  if (!currentPatientData) {
    return (
      <div className="space-y-5">
        <button
          onClick={() => navigate('/patients')}
          className="inline-flex items-center gap-1.5 text-sm font-medium text-gray-500 hover:text-gray-700 transition-colors"
        >
          <ArrowLeft className="h-4 w-4" />
          Back to patients
        </button>
        <EmptyState
          icon={AlertTriangle}
          title="Patient not found"
          sub="This patient doesn't exist or you don't have access"
        />
      </div>
    );
  }

  const tabCounts: Partial<Record<string, number>> = {
    medications: currentPatientData.prescriptions.length,
    labs: currentPatientData.tests.length,
    visits: currentPatientData.visits.length,
  };

  const tabs = [
    { value: 'overview', label: 'Overview', icon: Activity },
    { value: 'medications', label: 'Prescriptions', icon: Pill },
    { value: 'labs', label: 'Lab Results', icon: TestTube2 },
    { value: 'visits', label: 'Visits', icon: Calendar },
    { value: 'notes', label: 'Notes', icon: FileText },
    { value: 'wearables', label: 'Wearables', icon: Watch },
  ];

  return (
    <div className="space-y-6 pb-12">
      {/* Header */}
      <div className="flex items-center gap-3">
        <button
          onClick={() => navigate('/patients')}
          className="w-9 h-9 rounded-lg border border-gray-200 bg-white flex items-center justify-center text-gray-500 hover:bg-gray-50 hover:text-gray-800 transition-all shrink-0"
        >
          <ArrowLeft className="h-4 w-4" />
        </button>
        <div>
          <h1 className="text-2xl font-semibold text-gray-900 tracking-tight">{currentPatientData.user.dispName}</h1>
          <p className="text-sm text-gray-500 mt-0.5">Patient Medical Record</p>
        </div>
      </div>

      {/* Profile */}
      <ProfileCard
        data={currentPatientData}
        onViewPatientData={() => {
          if (!patientId) return;
          enterPatientView(patientId);
          navigate('/');
        }}
      />

      {/* Tabs */}
      <div>
        <div className="flex items-center gap-1 border-b border-gray-200 -mb-px">
          {tabs.map(t => (
            <button
              key={t.value}
              onClick={() => setActiveTab(t.value)}
              className={cn(
                'flex items-center gap-1.5 px-4 py-3 text-[13px] font-medium border-b-2 transition-colors',
                activeTab === t.value
                  ? 'border-primary text-primary'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              )}
            >
              <t.icon className="h-3.5 w-3.5" />
              {t.label}
              {tabCounts[t.value] != null && tabCounts[t.value]! > 0 && (
                <span className={cn(
                  'ml-1 text-[11px] tabular-nums',
                  activeTab === t.value ? 'text-primary/60' : 'text-gray-400'
                )}>
                  ({tabCounts[t.value]})
                </span>
              )}
            </button>
          ))}
        </div>

        <div className="mt-6">
          {activeTab === 'overview' && <OverviewTab data={currentPatientData} />}
          {activeTab === 'medications' && <MedicationsTab prescriptions={currentPatientData.prescriptions} />}
          {activeTab === 'labs' && <LabResultsTab tests={currentPatientData.tests} />}
          {activeTab === 'visits' && <VisitsTab visits={currentPatientData.visits} />}
          {activeTab === 'notes' && patientId && <NotesTab patientId={patientId} />}
          {activeTab === 'wearables' && patientId && <WearablesTab patientId={patientId} />}
        </div>
      </div>
    </div>
  );
}
