"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Users, Search, Filter, ChevronRight, Smartphone, AlertTriangle } from "lucide-react";

interface Patient {
  id: number;
  mrn: string;
  firstName: string;
  lastName: string;
  dateOfBirth: string;
  gender: string;
  appStatus: string | null;
  insuranceName: string | null;
  appLastLogin: string | null;
}

export default function PatientsPage() {
  const [patients, setPatients] = useState<Patient[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const router = useRouter();

  useEffect(() => {
    fetch("/api/patients")
      .then((r) => r.json())
      .then((d) => {
        setPatients(d.patients || []);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  const filtered = patients.filter(
    (p) =>
      `${p.firstName} ${p.lastName}`.toLowerCase().includes(search.toLowerCase()) ||
      p.mrn.includes(search)
  );

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-5">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Patient Panel</h1>
          <p className="text-sm text-slate-500 mt-0.5">
            {patients.length} attributed patients
          </p>
        </div>
      </div>

      {/* Panel Health Scorecard */}
      <div className="grid grid-cols-2 lg:grid-cols-5 gap-3">
        {[
          { label: "Total Active", value: patients.length, color: "text-clinical-600" },
          { label: "Care Gaps", value: "12%", color: "text-orange-600" },
          { label: "Controlled", value: "68%", color: "text-green-600" },
          { label: "App Engaged", value: "74%", color: "text-purple-600" },
          { label: "RPM Active", value: "45%", color: "text-teal-600" },
        ].map((s) => (
          <div key={s.label} className="bg-white border border-slate-200 rounded-xl p-4 text-center">
            <p className={`text-2xl font-bold ${s.color}`}>{s.value}</p>
            <p className="text-xs text-slate-500 mt-0.5">{s.label}</p>
          </div>
        ))}
      </div>

      {/* Search */}
      <div className="flex items-center gap-3">
        <div className="relative flex-1">
          <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search by name or MRN..."
            className="w-full pl-9 pr-4 py-2.5 bg-white border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-clinical-500"
          />
        </div>
        <button className="flex items-center gap-1.5 px-4 py-2.5 bg-white border border-slate-200 rounded-xl text-sm text-slate-600 hover:bg-slate-50 transition-colors">
          <Filter size={14} />
          Filters
        </button>
      </div>

      {/* Patient List */}
      <div className="bg-white border border-slate-200 rounded-xl">
        <div className="px-5 py-3 border-b border-slate-100 flex items-center gap-2">
          <Users size={14} className="text-clinical-600" />
          <h3 className="text-sm font-semibold text-slate-800">
            All Patients ({filtered.length})
          </h3>
        </div>
        {loading ? (
          <div className="p-8 text-center text-sm text-slate-400">Loading patients...</div>
        ) : (
          <div className="divide-y divide-slate-50">
            {filtered.map((patient) => {
              const age = new Date().getFullYear() - new Date(patient.dateOfBirth).getFullYear();
              return (
                <button
                  key={patient.id}
                  onClick={() => router.push(`/dashboard/patient/${patient.id}`)}
                  className="w-full flex items-center gap-4 px-5 py-3.5 hover:bg-slate-50 transition-colors text-left group"
                >
                  <div className="w-10 h-10 rounded-full bg-clinical-100 text-clinical-600 flex items-center justify-center text-sm font-bold shrink-0">
                    {patient.firstName[0]}{patient.lastName[0]}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold text-slate-800">
                      {patient.firstName} {patient.lastName}
                    </p>
                    <p className="text-xs text-slate-500">
                      MRN: {patient.mrn} • {age}{patient.gender === "Female" ? "F" : "M"} • {patient.insuranceName || "No insurance"}
                    </p>
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    {patient.appStatus === "active" && (
                      <Smartphone size={14} className="text-green-500" />
                    )}
                    {patient.appStatus === "inactive" && (
                      <Smartphone size={14} className="text-yellow-500" />
                    )}
                    <ChevronRight size={16} className="text-slate-300 group-hover:text-clinical-500 transition-colors" />
                  </div>
                </button>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
