import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { endpoints } from "@/lib/api";
import { fmtDate, fmtTime, fmtDateTime } from "@/lib/format";
import { SummaryCard } from "@/components/shared/SummaryCard";
import { StatusBadge } from "@/components/shared/StatusBadge";
import { EmptyState, LoadingBlock } from "@/components/shared/EmptyState";
import { OPD_STATUS, ADM_STATUS, ACTIVITY_META } from "@/lib/constants";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { ResponsiveContainer, AreaChart, Area, XAxis, Tooltip as RTooltip, CartesianGrid } from "recharts";
import * as Icons from "lucide-react";
import { PatientFormDrawer } from "@/components/patients/PatientFormDrawer";
import { OpdFormDrawer } from "@/components/opd/OpdFormDrawer";
import { AdmissionFormDrawer } from "@/components/ipd/AdmissionFormDrawer";
import { ChevronRight } from "lucide-react";

export default function Overview() {
  const navigate = useNavigate();
  const { data, isLoading } = useQuery({ queryKey: ["dashboard"], queryFn: endpoints.dashboard, refetchInterval: 15000 });
  const [regOpen, setRegOpen] = useState(false);
  const [opdOpen, setOpdOpen] = useState(false);
  const [admOpen, setAdmOpen] = useState(false);

  const k = data?.kpis;
  const occ = k?.occupancy == null ? "—" : `${k.occupancy}%`;

  return (
    <div className="space-y-5 animate-fade-in-up">
      <div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3">
        <div>
          <h1 className="text-2xl font-bold text-ink">Hospital overview</h1>
          <p className="text-sm text-subink mt-1">A clear view of today's patients, admissions and bed availability.</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button data-testid="action-register" onClick={() => setRegOpen(true)} className="bg-teal hover:bg-teal-hover text-white"><Icons.UserPlus size={16} className="mr-1.5" />Register patient</Button>
          <Button data-testid="action-new-opd" onClick={() => setOpdOpen(true)} variant="outline" className="border-teal/30 text-teal hover:bg-teal-soft"><Icons.Stethoscope size={16} className="mr-1.5" />New OPD visit</Button>
          <Button data-testid="action-admit" onClick={() => setAdmOpen(true)} variant="outline" className="border-clinical/30 text-clinical hover:bg-blue-50"><Icons.BedDouble size={16} className="mr-1.5" />Admit patient</Button>
        </div>
      </div>

      {isLoading ? <LoadingBlock rows={3} /> : (
        <>
          <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3">
            <SummaryCard testId="kpi-opd" label="OPD visits today" value={k.opd_visits_today} icon="ClipboardList" />
            <SummaryCard testId="kpi-waiting" label="Patients waiting" value={k.patients_waiting} icon="Clock" tint="#FFFBEB" iconColor="#B45309" />
            <SummaryCard testId="kpi-admissions" label="Active IPD admissions" value={k.active_admissions} icon="BedDouble" tint="#EFF6FF" iconColor="#1D4ED8" />
            <SummaryCard testId="kpi-available" label="Available beds" value={k.available_beds} icon="CheckCircle2" tint="#ECFDF5" iconColor="#047857" />
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <div><SummaryCard testId="kpi-occupancy" label="Bed occupancy" value={occ} icon="Activity" sub={k.occupancy_den ? `${k.occupancy_num}/${k.occupancy_den} operational beds` : null} /></div>
                </TooltipTrigger>
                <TooltipContent>Occupied ÷ operational beds (excludes Maintenance).</TooltipContent>
              </Tooltip>
            </TooltipProvider>
            <SummaryCard testId="kpi-discharges" label="Discharges today" value={k.discharges_today} icon="LogOut" tint="#F1F5F9" iconColor="#475569" />
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
            {/* OPD queue */}
            <div className="lg:col-span-2 rounded-2xl bg-white border border-hairline">
              <SectionHeader title="Today's OPD queue" onViewAll={() => navigate("/opd")} />
              {data.queue.length === 0 ? (
                <EmptyState icon="Coffee" title="Queue is clear" description="No patients are currently waiting or in consultation." />
              ) : (
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Token</TableHead><TableHead>Patient</TableHead><TableHead className="hidden md:table-cell">Doctor</TableHead>
                        <TableHead className="hidden md:table-cell">Dept</TableHead><TableHead>Time</TableHead><TableHead>Status</TableHead><TableHead></TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {data.queue.slice(0, 8).map((e) => (
                        <TableRow key={e.id} className="cursor-pointer" onClick={() => navigate("/opd")}>
                          <TableCell className="font-semibold tnum">{e.token}</TableCell>
                          <TableCell>
                            <div className="text-ink font-medium">{e.patient?.full_name}</div>
                            <div className="text-xs text-subink tnum">{e.patient?.patient_id}</div>
                          </TableCell>
                          <TableCell className="hidden md:table-cell text-subink">{e.doctor_name}</TableCell>
                          <TableCell className="hidden md:table-cell text-subink">{e.department}</TableCell>
                          <TableCell className="tnum text-subink">{fmtTime(e.scheduled_time || e.checkin_time)}</TableCell>
                          <TableCell><StatusBadge map={OPD_STATUS} status={e.status} /></TableCell>
                          <TableCell><ChevronRight size={16} className="text-subink" /></TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </div>

            {/* Bed availability by ward */}
            <div className="rounded-2xl bg-white border border-hairline">
              <SectionHeader title="Bed availability" onViewAll={() => navigate("/beds")} />
              <div className="p-3 space-y-2">
                {data.ward_availability.map((w) => {
                  const pct = w.total ? Math.round(((w.total - w.available) / w.total) * 100) : 0;
                  return (
                    <button key={w.ward_id} data-testid={`ward-avail-${w.ward_name}`} onClick={() => navigate("/beds")} className="w-full text-left rounded-xl border border-hairline p-3 hover:border-teal/40 transition-colors">
                      <div className="flex items-center justify-between">
                        <div className="text-sm font-medium text-ink">{w.ward_name}</div>
                        <div className="text-sm tnum"><span className="font-semibold text-teal">{w.available}</span><span className="text-subink">/{w.total}</span></div>
                      </div>
                      <div className="mt-2 h-1.5 rounded-full bg-slate-100 overflow-hidden">
                        <div className="h-full rounded-full bg-teal" style={{ width: `${pct}%` }} />
                      </div>
                      <div className="text-xs text-subink mt-1">{w.floor} · {w.available} available</div>
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
            {/* Active admissions */}
            <div className="lg:col-span-2 rounded-2xl bg-white border border-hairline">
              <SectionHeader title="Active IPD admissions" onViewAll={() => navigate("/ipd")} />
              {data.active_admissions.length === 0 ? (
                <EmptyState icon="BedDouble" title="No active admissions" />
              ) : (
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Patient</TableHead><TableHead className="hidden md:table-cell">Admission</TableHead><TableHead className="hidden lg:table-cell">Doctor</TableHead>
                        <TableHead>Ward / Bed</TableHead><TableHead className="hidden md:table-cell">Admitted</TableHead><TableHead>Stay</TableHead><TableHead></TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {data.active_admissions.slice(0, 6).map((a) => (
                        <TableRow key={a.id} className="cursor-pointer" onClick={() => navigate(`/ipd/${a.id}`)}>
                          <TableCell>
                            <div className="text-ink font-medium">{a.patient?.full_name}</div>
                            <div className="text-xs text-subink tnum">{a.patient?.patient_id}</div>
                          </TableCell>
                          <TableCell className="hidden md:table-cell tnum text-subink">{a.admission_id}</TableCell>
                          <TableCell className="hidden lg:table-cell text-subink">{a.doctor_name}</TableCell>
                          <TableCell className="text-subink"><span className="text-ink">{a.bed?.ward_name}</span> · <span className="tnum">{a.bed?.bed_number}</span></TableCell>
                          <TableCell className="hidden md:table-cell tnum text-subink">{fmtDate(a.admission_time)}</TableCell>
                          <TableCell className="tnum text-subink">{a.los?.label}</TableCell>
                          <TableCell><ChevronRight size={16} className="text-subink" /></TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </div>

            {/* Recent activity */}
            <div className="rounded-2xl bg-white border border-hairline">
              <SectionHeader title="Recent activity" />
              <div className="p-4 space-y-3 max-h-[360px] overflow-y-auto">
                {data.recent_activity.map((ev) => {
                  const meta = ACTIVITY_META[ev.kind] || { icon: "Dot", color: "#64748B" };
                  const Icon = Icons[meta.icon] || Icons.Dot;
                  return (
                    <div key={ev.id} className="flex gap-3">
                      <div className="h-7 w-7 rounded-lg flex items-center justify-center shrink-0" style={{ background: `${meta.color}14` }}>
                        <Icon size={14} style={{ color: meta.color }} />
                      </div>
                      <div className="min-w-0">
                        <div className="text-sm text-ink leading-snug">{ev.description}</div>
                        <div className="text-xs text-subink tnum mt-0.5">{fmtDateTime(ev.timestamp)}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          {/* 7-day OPD chart */}
          <div className="rounded-2xl bg-white border border-hairline p-4">
            <div className="text-sm font-semibold text-ink mb-3">OPD activity · last 7 days</div>
            <div className="h-48">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={data.opd_chart} margin={{ top: 5, right: 8, left: -20, bottom: 0 }}>
                  <defs>
                    <linearGradient id="opdFill" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="#0F766E" stopOpacity={0.25} />
                      <stop offset="100%" stopColor="#0F766E" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="#EEF2F6" vertical={false} />
                  <XAxis dataKey="label" tick={{ fontSize: 12, fill: "#526575" }} axisLine={false} tickLine={false} />
                  <RTooltip contentStyle={{ borderRadius: 12, border: "1px solid #E2E8F0", fontSize: 13 }} />
                  <Area type="monotone" dataKey="count" name="Visits" stroke="#0F766E" strokeWidth={2.5} fill="url(#opdFill)" />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </div>
        </>
      )}

      <PatientFormDrawer open={regOpen} onOpenChange={setRegOpen} />
      <OpdFormDrawer open={opdOpen} onOpenChange={setOpdOpen} />
      <AdmissionFormDrawer open={admOpen} onOpenChange={setAdmOpen} />
    </div>
  );
}

function SectionHeader({ title, onViewAll }) {
  return (
    <div className="flex items-center justify-between px-4 py-3 border-b border-hairline">
      <div className="text-sm font-semibold text-ink">{title}</div>
      {onViewAll && <button data-testid={`viewall-${title}`} onClick={onViewAll} className="text-xs font-medium text-teal hover:underline flex items-center gap-0.5">View all <ChevronRight size={13} /></button>}
    </div>
  );
}
