"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import {
  Clock,
  Video,
  AlertTriangle,
  ChevronRight,
  CheckCircle,
  XCircle,
  Archive,
  Users,
  Activity,
  Smartphone,
  TrendingUp,
  Heart,
  Zap,
  MessageCircle,
  FileText,
  Pill,
  Bot,
} from "lucide-react";

// Demo data - no API calls needed
const demoData = {
  appointments: [
    {
      id: 1,
      scheduledAt: new Date(new Date().setHours(9, 0, 0, 0)).toISOString(),
      duration: 30,
      visitType: "Follow-up",
      chiefComplaint: "Diabetes management - fatigue and increased thirst",
      status: "checked_in",
      noShowRisk: "Low",
      isTelehealth: false,
      patientId: 1,
      patientFirstName: "Mary",
      patientLastName: "Njeri",
      patientMrn: "KNH-447182",
      patientDob: "1968-03-14",
      patientGender: "Female",
      patientAppStatus: "active",
    },
    {
      id: 2,
      scheduledAt: new Date(new Date().setHours(9, 30, 0, 0)).toISOString(),
      duration: 30,
      visitType: "Follow-up",
      chiefComplaint: "Hypertension review, medication adjustment",
      status: "waiting",
      noShowRisk: "Low",
      isTelehealth: false,
      patientId: 2,
      patientFirstName: "John",
      patientLastName: "Kamau",
      patientMrn: "KNH-552930",
      patientDob: "1955-08-22",
      patientGender: "Male",
      patientAppStatus: "active",
    },
    {
      id: 3,
      scheduledAt: new Date(new Date().setHours(10, 0, 0, 0)).toISOString(),
      duration: 20,
      visitType: "Telehealth",
      chiefComplaint: "Anxiety follow-up, medication refill",
      status: "scheduled",
      noShowRisk: "High",
      isTelehealth: true,
      patientId: 3,
      patientFirstName: "Fatuma",
      patientLastName: "Hassan",
      patientMrn: "KNH-663871",
      patientDob: "1972-11-05",
      patientGender: "Female",
      patientAppStatus: "inactive",
    },
    {
      id: 4,
      scheduledAt: new Date(new Date().setHours(10, 30, 0, 0)).toISOString(),
      duration: 45,
      visitType: "New Patient",
      chiefComplaint: "Chronic low back pain evaluation",
      status: "scheduled",
      noShowRisk: "Medium",
      isTelehealth: false,
      patientId: 4,
      patientFirstName: "David",
      patientLastName: "Otieno",
      patientMrn: "KNH-774102",
      patientDob: "1990-06-18",
      patientGender: "Male",
      patientAppStatus: "active",
    },
    {
      id: 5,
      scheduledAt: new Date(new Date().setHours(11, 30, 0, 0)).toISOString(),
      duration: 30,
      visitType: "Annual Wellness",
      chiefComplaint: "Annual physical exam",
      status: "scheduled",
      noShowRisk: "Low",
      isTelehealth: false,
      patientId: 5,
      patientFirstName: "Agnes",
      patientLastName: "Wambui",
      patientMrn: "KNH-885419",
      patientDob: "1982-01-30",
      patientGender: "Female",
      patientAppStatus: "not_enrolled",
    },
    {
      id: 6,
      scheduledAt: new Date(new Date().setHours(14, 0, 0, 0)).toISOString(),
      duration: 30,
      visitType: "Follow-up",
      chiefComplaint: "CHF exacerbation, weight gain monitoring",
      status: "scheduled",
      noShowRisk: "Low",
      isTelehealth: false,
      patientId: 6,
      patientFirstName: "Joseph",
      patientLastName: "Mwangi",
      patientMrn: "KNH-996738",
      patientDob: "1948-12-03",
      patientGender: "Male",
      patientAppStatus: "active",
    },
  ],
  inbox: [
    {
      id: 1,
      category: "critical",
      priority: "critical",
      subject: "Critical Lab: HbA1c 10.2% - Mary Njeri",
      summary: "HbA1c has risen from 7.8% to 10.2% since last check. Immediate intervention recommended.",
      recommendedAction: "Review & Order",
      estimatedTime: "~2 minutes",
      patientId: 1,
    },
    {
      id: 2,
      category: "critical",
      priority: "critical",
      subject: "Deterioration Alert: Joseph Mwangi - Weight ↑2.3 kg in 3 days",
      summary: "RPM device data shows rapid weight gain consistent with fluid retention. BNP trending up.",
      recommendedAction: "Review & Order",
      estimatedTime: "~3 minutes",
      patientId: 6,
    },
    {
      id: 3,
      category: "urgent",
      priority: "urgent",
      subject: "Abnormal Result: Potassium 5.8 mEq/L - John Kamau",
      summary: "Potassium elevated above normal range. Patient on ACE inhibitor. Repeat lab recommended.",
      recommendedAction: "Review & Order",
      estimatedTime: "~1 minute",
      patientId: 2,
    },
    {
      id: 4,
      category: "routine",
      priority: "routine",
      subject: "Patient Message: David Otieno - Question about back exercises",
      summary: "Patient asking about recommended stretches and exercises before his appointment.",
      recommendedAction: "Reply",
      estimatedTime: "~30 seconds",
      patientId: 4,
    },
    {
      id: 5,
      category: "admin",
      priority: "routine",
      subject: "Unsigned Note: Fatuma Hassan - Visit 3 days ago",
      summary: "Telehealth visit note from 3 days ago remains unsigned. Action required within 72 hours.",
      recommendedAction: "Sign",
      estimatedTime: "~30 seconds",
      patientId: 3,
    },
    {
      id: 6,
      category: "patient_app",
      priority: "routine",
      subject: "Refill Request: Agnes Wambui - Sertraline 50mg",
      summary: "Patient submitted refill request via Clevora app. Last fill: 28 days ago. Adherence: 92%.",
      recommendedAction: "Approve",
      estimatedTime: "~15 seconds",
      patientId: 5,
    },
  ],
  alerts: [
    { id: 1, category: "Critical Results", title: "HbA1c 10.2% — Significant rise", description: "A1c rose from 7.8% to 10.2% in 3 months. Consider therapy intensification.", severity: "critical", patientId: 1, patientFirstName: "Mary", patientLastName: "Njeri" },
    { id: 2, category: "Deterioration Alert", title: "Weight gain 2.3 kg in 3 days — Joseph Mwangi", description: "Rapid weight gain in CHF patient. BNP trending upward. Consider diuretic adjustment.", severity: "critical", patientId: 6, patientFirstName: "Joseph", patientLastName: "Mwangi" },
    { id: 3, category: "Missed Medications", title: "Metformin adherence dropped to 78%", description: "Patient reports nausea with metformin. 5 missed doses in past 2 weeks.", severity: "high", patientId: 1, patientFirstName: "Mary", patientLastName: "Njeri" },
    { id: 4, category: "Critical Results", title: "Potassium 5.8 mEq/L — John Kamau", description: "Hyperkalemia in patient on ARB. ECG and repeat stat K+ recommended.", severity: "critical", patientId: 2, patientFirstName: "John", patientLastName: "Kamau" },
  ],
  panelStats: {
    totalPatients: 6,
    careGaps: 12,
    controlledChronic: 68,
    appEngaged: 74,
    rpmActive: 45,
  },
};

const statusConfig: Record<string, { color: string; label: string }> = {
  checked_in: { color: "bg-green-500", label: "Checked In" },
  waiting: { color: "bg-yellow-500", label: "Waiting" },
  in_progress: { color: "bg-blue-500", label: "In Progress" },
  scheduled: { color: "bg-slate-300", label: "Scheduled" },
  no_show: { color: "bg-red-500", label: "No Show" },
};

const priorityConfig: Record<string, { bg: string; text: string; border: string; dot: string }> = {
  critical: { bg: "bg-red-50", text: "text-red-700", border: "border-red-200", dot: "bg-red-500" },
  urgent: { bg: "bg-orange-50", text: "text-orange-700", border: "border-orange-200", dot: "bg-orange-500" },
  routine: { bg: "bg-yellow-50", text: "text-yellow-700", border: "border-yellow-200", dot: "bg-yellow-500" },
};

export default function DashboardPage() {
  const [data] = useState(demoData);
  const router = useRouter();

  const formatTime = (iso: string) => {
    const d = new Date(iso);
    return d.toLocaleTimeString("en-KE", { hour: "numeric", minute: "2-digit" });
  };

  const criticalAlerts = data.alerts.filter((a) => a.severity === "critical");
  const otherAlerts = data.alerts.filter((a) => a.severity !== "critical");

  return (
    <div className="flex h-full">
      {/* ── Center: Main Content ── */}
      <div className="flex-1 overflow-auto p-6 space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-slate-900">
              Karibu, Dr. Wanjiku 👋
            </h1>
            <p className="text-sm text-slate-500 mt-0.5">
              {new Date().toLocaleDateString("en-KE", {
                weekday: "long",
                month: "long",
                day: "numeric",
                year: "numeric",
              })}{" "}
              • {data.appointments.length} appointments today • Nairobi, Kenya 🇰🇪
            </p>
          </div>
          <div className="flex items-center gap-2">
            <span className="flex items-center gap-1.5 px-3 py-1.5 bg-green-50 text-green-700 rounded-full text-xs font-medium">
              <span className="w-1.5 h-1.5 bg-green-500 rounded-full animate-pulse" />
              System Online
            </span>
          </div>
        </div>

        {/* Panel Stats Cards */}
        <div className="grid grid-cols-2 lg:grid-cols-5 gap-3">
          {[
            { label: "Total Patients", value: data.panelStats.totalPatients, icon: Users, color: "text-clinical-600", bg: "bg-clinical-50" },
            { label: "Care Gaps", value: `${data.panelStats.careGaps}%`, icon: AlertTriangle, color: "text-orange-600", bg: "bg-orange-50" },
            { label: "Controlled", value: `${data.panelStats.controlledChronic}%`, icon: Heart, color: "text-green-600", bg: "bg-green-50" },
            { label: "App Engaged", value: `${data.panelStats.appEngaged}%`, icon: Smartphone, color: "text-purple-600", bg: "bg-purple-50" },
            { label: "RPM Active", value: `${data.panelStats.rpmActive}%`, icon: Activity, color: "text-teal-600", bg: "bg-teal-50" },
          ].map((s) => (
            <div key={s.label} className="bg-white rounded-xl border border-slate-200 p-4">
              <div className="flex items-center justify-between mb-2">
                <span className={`${s.bg} ${s.color} p-2 rounded-lg`}>
                  <s.icon size={16} />
                </span>
                <TrendingUp size={14} className="text-green-500" />
              </div>
              <p className="text-2xl font-bold text-slate-900">{s.value}</p>
              <p className="text-xs text-slate-500 mt-0.5">{s.label}</p>
            </div>
          ))}
        </div>

        {/* Today's Schedule */}
        <div className="bg-white rounded-xl border border-slate-200">
          <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
            <div className="flex items-center gap-2">
              <Clock size={16} className="text-clinical-600" />
              <h2 className="font-semibold text-slate-800">
                Today&apos;s Schedule
              </h2>
            </div>
            <span className="text-xs text-slate-400">
              {data.appointments.length} appointments
            </span>
          </div>
          <div className="divide-y divide-slate-50">
            {data.appointments.map((apt) => {
              const sc = statusConfig[apt.status] || statusConfig.scheduled;
              return (
                <button
                  key={apt.id}
                  onClick={() => router.push(`/dashboard/patient/${apt.patientId}`)}
                  className="w-full flex items-center gap-4 px-5 py-3.5 hover:bg-slate-50 transition-colors text-left group"
                >
                  <div className="text-center w-16 shrink-0">
                    <p className="text-sm font-semibold text-slate-800">
                      {formatTime(apt.scheduledAt)}
                    </p>
                    <p className="text-[10px] text-slate-400">
                      {apt.duration} min
                    </p>
                  </div>

                  <div className={`w-1 h-10 rounded-full ${sc.color}`} />

                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <p className="text-sm font-semibold text-slate-800 truncate">
                        {apt.patientFirstName} {apt.patientLastName}
                      </p>
                      {apt.isTelehealth && (
                        <span className="flex items-center gap-1 px-1.5 py-0.5 bg-blue-50 text-blue-600 rounded text-[10px] font-medium">
                          <Video size={10} /> Telehealth
                        </span>
                      )}
                      {apt.noShowRisk === "High" && (
                        <span className="px-1.5 py-0.5 bg-yellow-100 text-yellow-700 rounded text-[10px] font-medium">
                          ⚠️ High No-Show Risk
                        </span>
                      )}
                    </div>
                    <p className="text-xs text-slate-500 mt-0.5 truncate">
                      {apt.visitType} • {apt.chiefComplaint || "No complaint listed"}
                    </p>
                  </div>

                  <div className="flex items-center gap-2 shrink-0">
                    <span
                      className={`px-2 py-1 rounded-full text-[10px] font-medium ${
                        apt.status === "checked_in"
                          ? "bg-green-100 text-green-700"
                          : apt.status === "waiting"
                          ? "bg-yellow-100 text-yellow-700"
                          : "bg-slate-100 text-slate-600"
                      }`}
                    >
                      {sc.label}
                    </span>
                    {apt.patientAppStatus === "active" && (
                      <span className="text-[10px] text-green-500">📱</span>
                    )}
                    <ChevronRight
                      size={16}
                      className="text-slate-300 group-hover:text-clinical-500 transition-colors"
                    />
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* Intelligent Inbox */}
        <div className="bg-white rounded-xl border border-slate-200">
          <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
            <div className="flex items-center gap-2">
              <MessageCircle size={16} className="text-clinical-600" />
              <h2 className="font-semibold text-slate-800">
                Intelligent Inbox
              </h2>
            </div>
            <div className="flex items-center gap-2">
              <span className="px-2 py-0.5 bg-red-100 text-red-700 rounded-full text-[10px] font-semibold">
                {data.inbox.filter((m) => m.priority === "critical").length} Critical
              </span>
              <span className="text-xs text-slate-400">
                {data.inbox.length} unresolved
              </span>
            </div>
          </div>
          <div className="divide-y divide-slate-50">
            {data.inbox.map((msg) => {
              const pc = priorityConfig[msg.priority] || priorityConfig.routine;
              return (
                <div
                  key={msg.id}
                  className={`flex items-start gap-3 px-5 py-3.5 ${pc.bg} border-l-4 ${pc.border}`}
                >
                  <div className={`w-2 h-2 rounded-full ${pc.dot} mt-2 shrink-0`} />
                  <div className="flex-1 min-w-0">
                    <p className={`text-sm font-medium ${pc.text}`}>{msg.subject}</p>
                    <p className="text-xs text-slate-500 mt-1">{msg.summary}</p>
                    <div className="flex items-center gap-3 mt-2">
                      <span className="text-[10px] text-slate-400">
                        {msg.recommendedAction} • {msg.estimatedTime}
                      </span>
                    </div>
                  </div>
                  <div className="flex items-center gap-1 shrink-0">
                    <button className="p-1.5 hover:bg-white/50 rounded-lg transition-colors" title="Acknowledge">
                      <CheckCircle size={14} className="text-green-600" />
                    </button>
                    <button className="p-1.5 hover:bg-white/50 rounded-lg transition-colors" title="Dismiss">
                      <XCircle size={14} className="text-slate-400" />
                    </button>
                    <button className="p-1.5 hover:bg-white/50 rounded-lg transition-colors" title="Archive">
                      <Archive size={14} className="text-slate-400" />
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* ── Right Panel: AI Alerts & Agent Status ── */}
      <div className="w-80 bg-white border-l border-slate-200 overflow-auto hidden xl:block">
        {/* AI Priority Alerts */}
        <div className="p-4 border-b border-slate-100">
          <div className="flex items-center gap-2 mb-3">
            <Zap size={16} className="text-red-500" />
            <h3 className="text-sm font-semibold text-slate-800">
              AI Priority Alerts
            </h3>
            <span className="ml-auto px-1.5 py-0.5 bg-red-100 text-red-600 rounded-full text-[10px] font-semibold">
              {criticalAlerts.length}
            </span>
          </div>
          <div className="space-y-2">
            {criticalAlerts.map((alert) => (
              <button
                key={alert.id}
                onClick={() => {
                  if (alert.patientId) {
                    router.push(`/dashboard/patient/${alert.patientId}`);
                  }
                }}
                className="w-full text-left bg-red-50 border border-red-200 rounded-xl p-3 hover:bg-red-100 transition-colors"
              >
                <div className="flex items-start gap-2">
                  <AlertTriangle size={14} className="text-red-500 mt-0.5 shrink-0" />
                  <div>
                    <p className="text-xs font-semibold text-red-800">{alert.title}</p>
                    <p className="text-[10px] text-red-600 mt-1">{alert.description}</p>
                    {alert.patientFirstName && (
                      <p className="text-[10px] text-red-500 mt-1">
                        👤 {alert.patientFirstName} {alert.patientLastName}
                      </p>
                    )}
                  </div>
                </div>
              </button>
            ))}
            {otherAlerts.map((alert) => (
              <button
                key={alert.id}
                onClick={() => {
                  if (alert.patientId) {
                    router.push(`/dashboard/patient/${alert.patientId}`);
                  }
                }}
                className="w-full text-left bg-amber-50 border border-amber-200 rounded-xl p-3 hover:bg-amber-100 transition-colors"
              >
                <div className="flex items-start gap-2">
                  <AlertTriangle size={14} className="text-amber-500 mt-0.5 shrink-0" />
                  <div>
                    <p className="text-xs font-semibold text-amber-800">{alert.title}</p>
                    <p className="text-[10px] text-amber-600 mt-1">{alert.description}</p>
                  </div>
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* Neural Command Center */}
        <div className="p-4 border-b border-slate-100">
          <div className="flex items-center gap-2 mb-3">
            <Bot size={16} className="text-clinical-600" />
            <h3 className="text-sm font-semibold text-slate-800">
              AI Agent Status
            </h3>
          </div>
          <div className="space-y-2.5">
            {[
              { icon: "✅", agent: "SHA Claims Agent", detail: "Njeri, M — Claim submitted", action: "Awaiting approval" },
              { icon: "🔄", agent: "Pre-Auth Agent", detail: "Kamau, J — GLP-1 request", action: "Decision pending" },
              { icon: "📊", agent: "No-Show Prediction", detail: "3 high-risk appts tomorrow", action: "SMS reminders sent" },
              { icon: "🔍", agent: "CDI Monitor", detail: "4 charts flagged", action: "View list" },
              { icon: "💊", agent: "Med Reconciliation", detail: "2 discrepancies found", action: "Hassan, F & Otieno, D" },
            ].map((agent) => (
              <div
                key={agent.agent}
                className="bg-slate-50 rounded-lg p-3 cursor-pointer hover:bg-slate-100 transition-colors"
              >
                <div className="flex items-start gap-2">
                  <span className="text-sm">{agent.icon}</span>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs font-semibold text-slate-700">{agent.agent}</p>
                    <p className="text-[10px] text-slate-500 mt-0.5">{agent.detail}</p>
                    <p className="text-[10px] text-clinical-600 mt-0.5 font-medium">{agent.action}</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Quick Stats */}
        <div className="p-4">
          <h3 className="text-sm font-semibold text-slate-800 mb-3">
            Today&apos;s Efficiency
          </h3>
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <span className="text-xs text-slate-500 flex items-center gap-1.5">
                <FileText size={12} /> Notes Completed
              </span>
              <span className="text-xs font-semibold text-slate-700">3 / 6</span>
            </div>
            <div className="w-full h-1.5 bg-slate-100 rounded-full overflow-hidden">
              <div className="h-full w-1/2 bg-clinical-500 rounded-full" />
            </div>

            <div className="flex items-center justify-between">
              <span className="text-xs text-slate-500 flex items-center gap-1.5">
                <Pill size={12} /> Refill Requests
              </span>
              <span className="text-xs font-semibold text-slate-700">1 pending</span>
            </div>

            <div className="flex items-center justify-between">
              <span className="text-xs text-slate-500 flex items-center gap-1.5">
                <Clock size={12} /> Avg. Note Time
              </span>
              <span className="text-xs font-semibold text-green-600">4.2 min ↓</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
