import { useState, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
 Pill,
 Clock,
 AlertTriangle,
 FileText,
 ShieldAlert,
 BookOpen,
 Beaker,
 Hospital,
 Activity,
 ArrowLeft,
 User,
} from 'lucide-react';
import { format, isAfter, parseISO } from 'date-fns';
import { cn } from '../utils/helpers';
import { useHealthStore } from '../store/useHealthStore';
import type { APIPrescription, APIDiagnosis, APIHospitalVisit } from '../services/medical';

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

type DetailTab = 'overview' | 'instructions' | 'safety' | 'sideEffects';

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

function medName(p: APIPrescription) {
 return p.medication?.brandName || p.medication?.genericName || 'Unknown Medication';
}

function fmtDate(d?: string) {
 if (!d) return '—';
 try { return format(parseISO(d), 'MMM d, yyyy'); } catch { return d; }
}

/* ── Linked-data lookups ────────────────────────────────────────────────── */

function findLinkedDiagnosis(
 p: APIPrescription,
 diagnoses: APIDiagnosis[],
): APIDiagnosis | null {
 // Direct link via diagnosisId
 if (p.diagnosisId) {
  const direct = diagnoses.find(d => d._id === p.diagnosisId);
  if (direct) return direct;
 }
 // Reverse: find diagnosis whose relatedPrescriptions includes this prescription
 for (const d of diagnoses) {
  if (d.relatedPrescriptions?.some(rp => rp._id === p._id)) return d;
 }
 return null;
}

function findLinkedVisit(
 diag: APIDiagnosis | null,
 visits: APIHospitalVisit[],
): APIHospitalVisit | null {
 if (!diag) return null;
 for (const v of visits) {
  if (v.diagnoses?.includes(diag._id)) return v;
  if (v.populatedDiagnoses?.some(pd => pd._id === diag._id)) return v;
 }
 return null;
}

/* ── Reusable pieces ────────────────────────────────────────────────────── */

function InfoField({ label, children }: { label: string; children: React.ReactNode }) {
 return (
  <div>
   <span className="text-[11px] text-gray-400 block mb-0.5">{label}</span>
   <div className="text-sm text-gray-800">{children}</div>
  </div>
 );
}

function LongTextSection({ label, children }: { label: string; children: React.ReactNode }) {
 return (
  <div className="mb-6 last:mb-0">
   <h5 className="text-[11px] font-bold text-gray-400 uppercase tracking-wider mb-2.5">{label}</h5>
   <div className="text-[13.5px] text-gray-700 leading-[1.75] whitespace-pre-line">{children}</div>
  </div>
 );
}

/* ── Tab Content ────────────────────────────────────────────────────────── */

function OverviewTab({ p, linkedDiag, linkedVisit }: {
 p: APIPrescription;
 linkedDiag: APIDiagnosis | null;
 linkedVisit: APIHospitalVisit | null;
}) {
 const med = p.medication;
 const active = isActive(p);

 return (
  <div className="space-y-8">
   {/* Top: Medication + Prescription side by side */}
   <div className="grid grid-cols-1 md:grid-cols-2 gap-8">

    {/* Medication Card */}
    <div className="bg-white rounded-xl border border-gray-200/80 p-5 shadow-sm">
     <h4 className="text-xs font-bold text-gray-500 uppercase tracking-wider flex items-center gap-2 mb-4">
      <Pill className="w-3.5 h-3.5" /> Medication Details
     </h4>
     <div className="grid grid-cols-2 gap-x-6 gap-y-4">
      {med?.genericName && <InfoField label="Generic Name"><span className="font-medium">{med.genericName}</span></InfoField>}
      {med?.brandName && <InfoField label="Brand Name"><span className="font-medium">{med.brandName}</span></InfoField>}
      {med?.pharmClass && <InfoField label="Pharmaceutical Class">{med.pharmClass}</InfoField>}
      {med?.route && <InfoField label="Route"><span className="capitalize">{med.route}</span></InfoField>}
      <InfoField label="Dosage"><span className="font-medium">{p.dosage || '—'}</span></InfoField>
      <InfoField label="Frequency"><span className="font-medium">{p.frequency || '—'}</span></InfoField>
     </div>
     {p.instructions && (
      <div className="mt-4 pt-4 border-t border-dashed border-gray-200">
       <InfoField label="Special Instructions">
        <p className="text-gray-700 leading-relaxed">{p.instructions}</p>
       </InfoField>
      </div>
     )}
    </div>

    {/* Prescription Card */}
    <div className="bg-white rounded-xl border border-gray-200/80 p-5 shadow-sm">
     <h4 className="text-xs font-bold text-gray-500 uppercase tracking-wider flex items-center gap-2 mb-4">
      <FileText className="w-3.5 h-3.5" /> Prescription Info
     </h4>
    <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
      <InfoField label="Prescription ID"><span className="font-mono font-medium">{p.prescriptionId}</span></InfoField>
      <InfoField label="Status">
       <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>
      </InfoField>
      {p.doctorName && <InfoField label="Prescribed By"><span className="font-medium">{p.doctorName}</span></InfoField>}
      <InfoField label="Start Date">{fmtDate(p.startDate)}</InfoField>
      <InfoField label="End Date">{fmtDate(p.endDate)}</InfoField>
     </div>
    </div>
   </div>

   {/* Linked Diagnosis & Visit */}
   {(linkedDiag || linkedVisit) && (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
     {linkedDiag && (
      <div className="p-4 rounded-xl bg-blue-50/50 border border-blue-100/80">
       <div className="flex items-start gap-3">
        <div className="w-9 h-9 rounded-lg bg-blue-100 flex items-center justify-center shrink-0 mt-0.5">
         <Activity className="w-4 h-4 text-blue-600" />
        </div>
        <div className="min-w-0">
         <p className="text-[11px] text-blue-500 font-semibold uppercase tracking-wider">Linked Diagnosis</p>
         <p className="text-sm font-medium text-gray-900 mt-1">{linkedDiag.disease?.name || 'Diagnosis'}</p>
         <div className="flex items-center gap-3 mt-1.5 text-[11px] text-gray-500">
          <span className="font-mono bg-white/80 px-1.5 py-0.5 rounded border border-blue-100">{linkedDiag.icdCode}</span>
          {linkedDiag.diagnosisDate && <span>{fmtDate(linkedDiag.diagnosisDate)}</span>}
          {linkedDiag.practitioner && (
           <span className="flex items-center gap-1"><User className="w-3 h-3" />{linkedDiag.practitioner}</span>
          )}
         </div>
         {linkedDiag.notes && (
          <p className="text-xs text-gray-500 mt-2 leading-relaxed">{linkedDiag.notes}</p>
         )}
        </div>
       </div>
      </div>
     )}

     {linkedVisit && (
      <div className="p-4 rounded-xl bg-violet-50/50 border border-violet-100/80">
       <div className="flex items-start gap-3">
        <div className="w-9 h-9 rounded-lg bg-violet-100 flex items-center justify-center shrink-0 mt-0.5">
         <Hospital className="w-4 h-4 text-violet-600" />
        </div>
        <div className="min-w-0">
         <p className="text-[11px] text-violet-500 font-semibold uppercase tracking-wider">Hospital Visit</p>
         <p className="text-sm font-medium text-gray-900 mt-1">{linkedVisit.hospital}</p>
         <div className="flex items-center gap-3 mt-1.5 text-[11px] text-gray-500 flex-wrap">
          {linkedVisit.visitDate && <span>{fmtDate(linkedVisit.visitDate)}</span>}
          {linkedVisit.department && <span>· {linkedVisit.department}</span>}
          {linkedVisit.doctorName && (
           <span className="flex items-center gap-1"><User className="w-3 h-3" />{linkedVisit.doctorName}</span>
          )}
         </div>
         {linkedVisit.dischargeSummary && (
          <p className="text-xs text-gray-500 mt-2 leading-relaxed line-clamp-3">{linkedVisit.dischargeSummary}</p>
         )}
        </div>
       </div>
      </div>
     )}
    </div>
   )}
  </div>
 );
}

function InstructionsTab({ p }: { p: APIPrescription }) {
 const med = p.medication;
 const hasContent = med?.indications || med?.dosageAndAdministration || p.instructions;

 if (!hasContent) {
  return (
   <div className="flex flex-col items-center justify-center py-16 text-gray-400">
    <BookOpen className="w-10 h-10 mb-3 text-gray-300" />
    <p className="text-sm font-medium">No instructions or indications available</p>
    <p className="text-xs text-gray-400 mt-1">This medication doesn't have detailed instruction data.</p>
   </div>
  );
 }

 return (
  <div className="max-w-3xl">
   {med?.indications && <LongTextSection label="Indications">{med.indications}</LongTextSection>}
   {med?.dosageAndAdministration && <LongTextSection label="Dosage & Administration">{med.dosageAndAdministration}</LongTextSection>}
   {p.instructions && <LongTextSection label="Prescriber Instructions">{p.instructions}</LongTextSection>}
  </div>
 );
}

function SafetyTab({ p }: { p: APIPrescription }) {
 const med = p.medication;
 const hasContent = med?.warnings || med?.contraindications || med?.drugInteractions;

 if (!hasContent) {
  return (
   <div className="flex flex-col items-center justify-center py-16 text-gray-400">
    <ShieldAlert className="w-10 h-10 mb-3 text-gray-300" />
    <p className="text-sm font-medium">No safety data available</p>
    <p className="text-xs text-gray-400 mt-1">This medication doesn't have safety information on file.</p>
   </div>
  );
 }

 return (
  <div className="max-w-3xl">
   {med?.warnings && <LongTextSection label="Warnings & Precautions">{med.warnings}</LongTextSection>}
   {med?.contraindications && <LongTextSection label="Contraindications">{med.contraindications}</LongTextSection>}
   {med?.drugInteractions && <LongTextSection label="Drug Interactions">{med.drugInteractions}</LongTextSection>}
  </div>
 );
}

function SideEffectsTab({ p }: { p: APIPrescription }) {
 const med = p.medication;

 if (!med?.adverseReactions) {
  return (
   <div className="flex flex-col items-center justify-center py-16 text-gray-400">
    <Beaker className="w-10 h-10 mb-3 text-gray-300" />
    <p className="text-sm font-medium">No adverse reaction data available</p>
    <p className="text-xs text-gray-400 mt-1">This medication doesn't have side effect information on file.</p>
   </div>
  );
 }

 return (
  <div className="max-w-3xl">
   <LongTextSection label="Adverse Reactions">{med.adverseReactions}</LongTextSection>
  </div>
 );
}

/* ── Tab config ─────────────────────────────────────────────────────────── */

const TABS: { key: DetailTab; label: string; icon: typeof FileText }[] = [
 { key: 'overview',     label: 'Overview',      icon: FileText },
 { key: 'instructions', label: 'Instructions',   icon: BookOpen },
 { key: 'safety',       label: 'Safety',         icon: ShieldAlert },
 { key: 'sideEffects',  label: 'Side Effects',   icon: AlertTriangle },
];

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

export function PrescriptionDetailPage() {
 const { id } = useParams<{ id: string }>();
 const navigate = useNavigate();
 const [tab, setTab] = useState<DetailTab>('overview');

 const rawPrescriptions = useHealthStore((s) => s._rawPrescriptions);
 const rawDiagnoses = useHealthStore((s) => s._rawDiagnoses);
 const rawVisits = useHealthStore((s) => s._rawVisits);
 const loadedUserId = useHealthStore((s) => s._loadedUserId);

 const prescription = useMemo(
  () => rawPrescriptions.find(p => p._id === id) || null,
  [rawPrescriptions, id]
 );

 const linkedDiag = useMemo(
  () => prescription ? findLinkedDiagnosis(prescription, rawDiagnoses) : null,
  [prescription, rawDiagnoses]
 );

 const linkedVisit = useMemo(
  () => findLinkedVisit(linkedDiag, rawVisits),
  [linkedDiag, rawVisits]
 );

 // Loading
 if (loadedUserId === null) {
  return (
   <div className="flex items-center justify-center py-32">
    <div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full" />
   </div>
  );
 }

 // Not found
 if (!prescription) {
  return (
   <div className="flex flex-col items-center justify-center py-32">
    <Pill className="w-12 h-12 text-gray-300 mb-4" />
    <h2 className="text-lg font-semibold text-gray-900 mb-1">Prescription not found</h2>
    <p className="text-sm text-gray-500 mb-6">This prescription may have been removed or the link is invalid.</p>
    <button
     onClick={() => navigate('/prescriptions')}
     className="inline-flex items-center gap-2 px-4 py-2 bg-gray-900 text-white rounded-lg text-sm font-medium hover:bg-gray-800 transition-colors"
    >
     <ArrowLeft className="w-4 h-4" />
     Back to Prescriptions
    </button>
   </div>
  );
 }

 const p = prescription;
 const active = isActive(p);

 return (
  <div className="pb-20">
   {/* Back button */}
   <button
    onClick={() => navigate('/prescriptions')}
    className="inline-flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-700 mb-6 transition-colors"
   >
    <ArrowLeft className="w-4 h-4" />
    Back to Prescriptions
   </button>

   {/* Prescription Paper Card */}
   <div className={cn(
    "relative rounded-2xl overflow-hidden",
    "bg-gradient-to-b from-stone-50/80 to-white",
    "border border-gray-200/70",
    "shadow-[0_1px_3px_rgba(0,0,0,0.06),0_8px_24px_rgba(0,0,0,0.04)]",
   )}>
    {/* Top accent line */}
    <div className={cn(
     "absolute top-0 left-0 right-0 h-[3px]",
     active ? "bg-gradient-to-r from-emerald-400 to-teal-400" : "bg-gradient-to-r from-gray-300 to-gray-200"
    )} />

    {/* Header */}
    <div className="px-8 pt-7 pb-5 border-b border-gray-100">
     <div className="flex items-start justify-between gap-4">
      <div className="flex items-center gap-5">
       <div className={cn(
        "w-14 h-14 rounded-2xl flex items-center justify-center shrink-0",
        "shadow-sm",
        active
         ? "bg-gradient-to-br from-emerald-50 to-teal-50 border border-emerald-200/60"
         : "bg-gray-100 border border-gray-200/60"
       )}>
        <span className={cn(
         "text-2xl font-bold italic",
         active ? "text-emerald-600" : "text-gray-400"
        )}>Rx</span>
       </div>
       <div>
        <h1 className="text-xl font-semibold text-gray-900">{medName(p)}</h1>
        {p.medication?.genericName && p.medication.brandName && (
         <p className="text-sm text-gray-400 mt-0.5">{p.medication.genericName}</p>
        )}
        <div className="flex items-center gap-4 mt-2 flex-wrap">
         <span className="text-xs text-gray-400 font-mono">{p.prescriptionId}</span>
         <span className="text-gray-200">·</span>
         <span className="flex items-center gap-1 text-xs text-gray-400">
          <Clock className="w-3 h-3" />
          {fmtDate(p.startDate)} — {fmtDate(p.endDate)}
         </span>
         {p.doctorName && (
          <>
           <span className="text-gray-200">·</span>
           <span className="flex items-center gap-1 text-xs text-gray-400">
            <User className="w-3 h-3" />
            {p.doctorName}
           </span>
          </>
         )}
        </div>
       </div>
      </div>
      <span className={cn(
       "inline-flex items-center px-3 py-1.5 rounded-lg text-xs font-bold uppercase tracking-wide shrink-0",
       active
        ? "bg-emerald-50 text-emerald-600 border border-emerald-200/60"
        : "bg-gray-100 text-gray-500 border border-gray-200/60"
      )}>
       {active ? 'Active' : 'Expired'}
      </span>
     </div>
    </div>

    {/* Tab Bar */}
    <div className="px-8 border-b border-gray-100 bg-white/60">
     <div className="flex gap-1 -mb-px">
      {TABS.map(({ key, label, icon: Icon }) => (
       <button
        key={key}
        onClick={() => setTab(key)}
        className={cn(
         "flex items-center gap-2 px-5 py-3 text-sm font-medium border-b-2 transition-all",
         tab === key
          ? "border-gray-900 text-gray-900"
          : "border-transparent text-gray-400 hover:text-gray-600 hover:border-gray-200"
        )}
       >
        <Icon className="w-4 h-4" />
        {label}
       </button>
      ))}
     </div>
    </div>

    {/* Tab Content */}
    <div className="px-8 py-7">
     {tab === 'overview' && <OverviewTab p={p} linkedDiag={linkedDiag} linkedVisit={linkedVisit} />}
     {tab === 'instructions' && <InstructionsTab p={p} />}
     {tab === 'safety' && <SafetyTab p={p} />}
     {tab === 'sideEffects' && <SideEffectsTab p={p} />}
    </div>
   </div>
  </div>
 );
}
