"use client";

import { useState, use } from "react";
import { useRouter } from "next/navigation";
import {
  ArrowLeft,
  Activity,
  FileText,
  Pill,
  FlaskConical,
  ClipboardList,
  Users,
  CalendarDays,
  Smartphone,
  DollarSign,
  History,
  Bot,
} from "lucide-react";
import { SummaryTab } from "@/components/patient/SummaryTab";
import { NotesTab } from "@/components/patient/NotesTab";
import { MedicationsTab } from "@/components/patient/MedicationsTab";
import { ResultsTab } from "@/components/patient/ResultsTab";
import { OrdersTab } from "@/components/patient/OrdersTab";
import { CareTeamTab } from "@/components/patient/CareTeamTab";
import { CarePlanTab } from "@/components/patient/CarePlanTab";
import { AppActivityTab } from "@/components/patient/AppActivityTab";
import { FinancialTab } from "@/components/patient/FinancialTab";
import { HistoryTab } from "@/components/patient/HistoryTab";
import { AISidebar } from "@/components/patient/AISidebar";
import type { PatientData } from "@/lib/types";

// Demo patient data
const demoPatients: Record<string, PatientData> = {
  "1": {
    patient: {
      id: 1,
      mrn: "KNH-447182",
      firstName: "Mary",
      lastName: "Njeri",
      dateOfBirth: "1968-03-14",
      gender: "Female",
      phone: "+254 722 345 678",
      email: "mary.njeri@gmail.com",
      allergies: "Penicillin (Anaphylaxis), Sulfa (Rash)",
      codeStatus: "Full Code",
      insuranceName: "SHA (Social Health Authority)",
      insuranceStatus: "Verified",
      pcpId: 1,
      appStatus: "active",
      appLastLogin: new Date(Date.now() - 2 * 3600000).toISOString(),
      roomNumber: "Ward 4B-214",
      photoUrl: null,
      createdAt: new Date().toISOString(),
      pcp: { firstName: "Grace", lastName: "Wanjiku" },
    },
    problems: [
      { id: 1, patientId: 1, name: "Type 2 Diabetes Mellitus", icdCode: "E11.65", status: "Active", controlStatus: "Uncontrolled", lastResult: "A1C: 10.2% (1 week ago)", patientReported: "Blood sugar running high, increased thirst", aiRecommendation: "Consider GLP-1 RA addition or insulin initiation", onsetDate: null, createdAt: new Date().toISOString() },
      { id: 2, patientId: 1, name: "Essential Hypertension", icdCode: "I10", status: "Active", controlStatus: "Controlled", lastResult: "BP: 128/78 (last visit)", patientReported: "No complaints", aiRecommendation: "Continue current regimen", onsetDate: null, createdAt: new Date().toISOString() },
      { id: 3, patientId: 1, name: "Hyperlipidemia", icdCode: "E78.5", status: "Active", controlStatus: "Stable", lastResult: "LDL: 2.5 mmol/L (2 months ago)", patientReported: null, aiRecommendation: "Recheck lipid panel at next visit", onsetDate: null, createdAt: new Date().toISOString() },
    ],
    medications: [
      { id: 1, patientId: 1, name: "Metformin", dose: "1000mg", route: "Oral", frequency: "Twice daily", prescriberId: 1, startDate: null, indication: "Type 2 Diabetes", adherenceRate: 78, fillStatus: "Filled", isActive: true, createdAt: new Date().toISOString() },
      { id: 2, patientId: 1, name: "Lisinopril", dose: "20mg", route: "Oral", frequency: "Once daily", prescriberId: 1, startDate: null, indication: "Hypertension", adherenceRate: 92, fillStatus: "Filled", isActive: true, createdAt: new Date().toISOString() },
      { id: 3, patientId: 1, name: "Atorvastatin", dose: "40mg", route: "Oral", frequency: "Once daily at bedtime", prescriberId: 1, startDate: null, indication: "Hyperlipidemia", adherenceRate: 85, fillStatus: "Filled", isActive: true, createdAt: new Date().toISOString() },
    ],
    labs: [
      { id: 1, patientId: 1, testName: "Hemoglobin A1c", value: "10.2", unit: "%", referenceRange: "4.0-5.6", status: "Critical", category: "Laboratory", resultDate: new Date(Date.now() - 7 * 86400000).toISOString(), isAcknowledged: false, aiInterpretation: "Significant rise from 7.8% three months ago. Indicates poor glycemic control. Consider intensification of diabetes management.", createdAt: new Date().toISOString() },
      { id: 2, patientId: 1, testName: "Hemoglobin A1c", value: "7.8", unit: "%", referenceRange: "4.0-5.6", status: "Abnormal", category: "Laboratory", resultDate: new Date(Date.now() - 97 * 86400000).toISOString(), isAcknowledged: true, aiInterpretation: "Above target but improving from prior value.", createdAt: new Date().toISOString() },
      { id: 3, patientId: 1, testName: "Fasting Glucose", value: "12.1", unit: "mmol/L", referenceRange: "3.9-5.6", status: "Critical", category: "Laboratory", resultDate: new Date(Date.now() - 7 * 86400000).toISOString(), isAcknowledged: false, aiInterpretation: "Significantly elevated fasting glucose consistent with A1c trend.", createdAt: new Date().toISOString() },
      { id: 4, patientId: 1, testName: "Creatinine", value: "80", unit: "μmol/L", referenceRange: "53-106", status: "Normal", category: "Laboratory", resultDate: new Date(Date.now() - 7 * 86400000).toISOString(), isAcknowledged: true, aiInterpretation: "Within normal limits. eGFR >60.", createdAt: new Date().toISOString() },
      { id: 5, patientId: 1, testName: "LDL Cholesterol", value: "2.5", unit: "mmol/L", referenceRange: "<2.6", status: "Normal", category: "Laboratory", resultDate: new Date(Date.now() - 60 * 86400000).toISOString(), isAcknowledged: true, aiInterpretation: "At goal on current statin therapy.", createdAt: new Date().toISOString() },
    ],
    orders: [
      { id: 1, patientId: 1, providerId: 1, orderName: "Comprehensive Metabolic Panel", orderType: "Laboratory", status: "Resulted", priority: "Routine", orderedAt: new Date().toISOString(), createdAt: new Date().toISOString() },
      { id: 2, patientId: 1, providerId: 1, orderName: "Hemoglobin A1c", orderType: "Laboratory", status: "Resulted", priority: "Routine", orderedAt: new Date().toISOString(), createdAt: new Date().toISOString() },
      { id: 3, patientId: 1, providerId: 1, orderName: "Diabetic Eye Exam Referral - KNH Ophthalmology", orderType: "Referral", status: "Sent", priority: "Routine", orderedAt: new Date().toISOString(), createdAt: new Date().toISOString() },
    ],
    goals: [
      { id: 1, patientId: 1, goalName: "Hemoglobin A1c", targetValue: "< 7.0", currentValue: "10.2", unit: "%", trend: "up", status: "Off Track", createdAt: new Date().toISOString() },
      { id: 2, patientId: 1, goalName: "Systolic Blood Pressure", targetValue: "< 130", currentValue: "128", unit: "mmHg", trend: "stable", status: "At Goal", createdAt: new Date().toISOString() },
      { id: 3, patientId: 1, goalName: "Weight", targetValue: "70", currentValue: "87", unit: "kg", trend: "down", status: "Improving", createdAt: new Date().toISOString() },
      { id: 4, patientId: 1, goalName: "LDL Cholesterol", targetValue: "< 2.6", currentValue: "2.5", unit: "mmol/L", trend: "stable", status: "At Goal", createdAt: new Date().toISOString() },
    ],
    vitals: Array.from({ length: 14 }, (_, i) => [
      { id: i * 3 + 1, patientId: 1, type: "blood_glucose", value: String(10 + Math.round(Math.random() * 3)), unit: "mmol/L", recordedAt: new Date(Date.now() - i * 86400000).toISOString(), source: "device", createdAt: new Date().toISOString() },
      { id: i * 3 + 2, patientId: 1, type: "systolic_bp", value: String(125 + Math.round(Math.random() * 10)), unit: "mmHg", recordedAt: new Date(Date.now() - i * 86400000).toISOString(), source: "device", createdAt: new Date().toISOString() },
      { id: i * 3 + 3, patientId: 1, type: "weight", value: String((87 - i * 0.1).toFixed(1)), unit: "kg", recordedAt: new Date(Date.now() - i * 86400000).toISOString(), source: "device", createdAt: new Date().toISOString() },
    ]).flat(),
    notes: [
      {
        id: 1,
        patientId: 1,
        providerId: 1,
        noteType: "SOAP",
        content: `SUBJECTIVE:\nPatient presents for diabetes follow-up. Reports increased fatigue and polydipsia over the past 3 weeks. Home glucose readings 10-13 mmol/L fasting (usual 7-9 mmol/L). Attributes worsening to increased stress at work and reduced exercise. Denies polyuria, blurred vision, or neuropathy symptoms.\n\nOBJECTIVE:\nVitals: BP 128/78, HR 76, Temp 36.9°C, Weight 87 kg (down 1.5 kg)\nGeneral: Alert, NAD\nCV: RRR, no murmurs\nExtremities: No edema, intact pedal pulses\nNeuro: Intact monofilament sensation bilaterally\n\nASSESSMENT:\n1. Type 2 Diabetes - Uncontrolled, A1c rising\n2. Hypertension - Controlled on current regimen\n3. Hyperlipidemia - At goal\n\nPLAN:\n1. Diabetes: Consider adding GLP-1 RA. Recheck A1c in 3 months.\n2. Continue lisinopril and atorvastatin\n3. Referral to diabetes education program at Kenyatta National Hospital\n4. F/U 3 months`,
        status: "Signed",
        visitDate: new Date(Date.now() - 90 * 86400000).toISOString(),
        createdAt: new Date().toISOString(),
      },
    ],
  },
};

// Generate default patient data for other IDs
const generateDefaultPatient = (id: string): PatientData => ({
  patient: {
    id: parseInt(id),
    mrn: `KNH-${id.padStart(6, "0")}`,
    firstName: "Patient",
    lastName: id,
    dateOfBirth: "1970-01-01",
    gender: "Unknown",
    phone: "+254 700 000 000",
    email: null,
    allergies: "None Known",
    codeStatus: "Full Code",
    insuranceName: "SHA (Social Health Authority)",
    insuranceStatus: "Verified",
    pcpId: 1,
    appStatus: "active",
    appLastLogin: new Date().toISOString(),
    roomNumber: null,
    photoUrl: null,
    createdAt: new Date().toISOString(),
    pcp: { firstName: "Grace", lastName: "Wanjiku" },
  },
  problems: [],
  medications: [],
  labs: [],
  orders: [],
  goals: [],
  vitals: [],
  notes: [],
});

const tabs = [
  { id: "summary", label: "Summary", icon: Activity },
  { id: "notes", label: "Notes", icon: FileText },
  { id: "medications", label: "Medications", icon: Pill },
  { id: "results", label: "Results", icon: FlaskConical },
  { id: "orders", label: "Orders", icon: ClipboardList },
  { id: "care-team", label: "Care Team", icon: Users },
  { id: "care-plan", label: "Care Plan", icon: CalendarDays },
  { id: "app-activity", label: "App Activity", icon: Smartphone },
  { id: "financial", label: "Financial", icon: DollarSign },
  { id: "history", label: "History", icon: History },
];

export default function PatientChartPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = use(params);
  const data = demoPatients[id] || generateDefaultPatient(id);
  const [activeTab, setActiveTab] = useState("summary");
  const [showAI, setShowAI] = useState(true);
  const router = useRouter();

  const { patient } = data;
  const age = new Date().getFullYear() - new Date(patient.dateOfBirth).getFullYear();
  const genderLetter = patient.gender === "Female" ? "F" : patient.gender === "Male" ? "M" : "O";

  const appStatusConfig: Record<string, { color: string; label: string }> = {
    active: { color: "text-green-600", label: "🟢 Active" },
    inactive: { color: "text-yellow-600", label: "🟡 Inactive" },
    not_enrolled: { color: "text-slate-500", label: "⚫ Not Enrolled" },
  };
  const appSt = appStatusConfig[patient.appStatus || "not_enrolled"] || appStatusConfig.not_enrolled;

  const criticalAlerts = data.labs.filter((l) => l.status === "Critical").length;

  const renderTab = () => {
    switch (activeTab) {
      case "summary": return <SummaryTab data={data} />;
      case "notes": return <NotesTab data={data} />;
      case "medications": return <MedicationsTab data={data} />;
      case "results": return <ResultsTab data={data} />;
      case "orders": return <OrdersTab data={data} />;
      case "care-team": return <CareTeamTab data={data} />;
      case "care-plan": return <CarePlanTab data={data} />;
      case "app-activity": return <AppActivityTab data={data} />;
      case "financial": return <FinancialTab data={data} />;
      case "history": return <HistoryTab data={data} />;
      default: return <SummaryTab data={data} />;
    }
  };

  return (
    <div className="flex flex-col h-full">
      {/* Patient Identity Bar */}
      <div className="bg-white border-b border-slate-200 px-5 py-3 shrink-0">
        <div className="flex items-center gap-4">
          <button
            onClick={() => router.push("/dashboard")}
            className="p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400"
          >
            <ArrowLeft size={18} />
          </button>

          {/* Patient Avatar */}
          <div className="w-10 h-10 rounded-full bg-gradient-to-br from-clinical-500 to-clinical-700 text-white flex items-center justify-center text-sm font-bold shrink-0">
            {patient.firstName[0]}{patient.lastName[0]}
          </div>

          {/* Patient Info */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <h2 className="text-base font-bold text-slate-900">
                {patient.firstName} {patient.lastName}
              </h2>
              <span className="text-xs text-slate-500">
                DOB: {new Date(patient.dateOfBirth).toLocaleDateString()} ({age}{genderLetter})
              </span>
              <span className="text-xs text-slate-400">MRN: {patient.mrn}</span>
            </div>
            <div className="flex items-center gap-3 mt-0.5 flex-wrap text-[11px]">
              <span className="text-red-600 font-medium">
                ⚠️ Allergies: {patient.allergies || "NKDA"}
              </span>
              <span className="text-slate-400">|</span>
              <span className="text-slate-600">Code Status: {patient.codeStatus}</span>
              {patient.pcp && (
                <>
                  <span className="text-slate-400">|</span>
                  <span className="text-slate-600">
                    PCP: Dr. {patient.pcp.firstName} {patient.pcp.lastName}
                  </span>
                </>
              )}
              {patient.roomNumber && (
                <>
                  <span className="text-slate-400">|</span>
                  <span className="text-slate-600">Room: {patient.roomNumber}</span>
                </>
              )}
              <span className="text-slate-400">|</span>
              <span className={appSt.color}>
                📱 App: {appSt.label}
              </span>
              {criticalAlerts > 0 && (
                <>
                  <span className="text-slate-400">|</span>
                  <span className="text-red-600 font-semibold">
                    ⚠️ {criticalAlerts} Critical Alert{criticalAlerts > 1 ? "s" : ""}
                  </span>
                </>
              )}
              <span className="text-slate-400">|</span>
              <span className="text-slate-600">
                Insurance: {patient.insuranceName} — {patient.insuranceStatus} ✓
              </span>
            </div>
          </div>

          {/* AI Toggle */}
          <button
            onClick={() => setShowAI(!showAI)}
            className={`p-2 rounded-xl transition-colors ${
              showAI ? "bg-clinical-50 text-clinical-600" : "bg-slate-100 text-slate-400"
            }`}
            title="Toggle AI Assistant"
          >
            <Bot size={18} />
          </button>
        </div>
      </div>

      {/* Tab Navigation */}
      <div className="bg-white border-b border-slate-200 px-5 shrink-0">
        <div className="flex gap-0.5 overflow-x-auto">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-1.5 px-3 py-2.5 text-xs font-medium border-b-2 transition-colors whitespace-nowrap ${
                activeTab === tab.id
                  ? "border-clinical-600 text-clinical-700"
                  : "border-transparent text-slate-500 hover:text-slate-700"
              }`}
            >
              <tab.icon size={14} />
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {/* Content Area with Optional AI Sidebar */}
      <div className="flex flex-1 overflow-hidden">
        <div className="flex-1 overflow-auto p-5">{renderTab()}</div>

        {/* AI Assistant Sidebar */}
        {showAI && (
          <div className="w-80 border-l border-slate-200 bg-white shrink-0 hidden lg:block overflow-hidden">
            <AISidebar data={data} />
          </div>
        )}
      </div>
    </div>
  );
}
