import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { Users, Pill, Stethoscope, Plus } from "lucide-react";
import Link from "next/link";
import Sidebar from "./_components/Sidebar";
import StatCard from "./_components/StatCard";
import PatientActions from "./_components/PatientActions";

function calculateAge(dob: Date): number {
  const today = new Date();
  let age = today.getFullYear() - dob.getFullYear();
  const monthDiff = today.getMonth() - dob.getMonth();
  if (
    monthDiff < 0 ||
    (monthDiff === 0 && today.getDate() < dob.getDate())
  ) {
    age--;
  }
  return age;
}

function getStageBadgeClass(stage: string): string {
  const lower = stage.toLowerCase();
  if (lower.includes("early"))
    return "bg-emerald-900/30 text-emerald-400 border-emerald-800";
  if (lower.includes("middle"))
    return "bg-amber-900/30 text-amber-400 border-amber-800";
  if (lower.includes("late"))
    return "bg-rose-900/30 text-rose-400 border-rose-800";
  return "bg-zinc-800 text-zinc-400 border-zinc-700";
}

export default async function DashboardPage() {
  const session = await auth();

  if (!session?.user?.id) {
    redirect("/login");
  }

  if (session.user.role === "DOCTOR") {
    redirect("/dashboard/doctor");
  }

  if (session.user.role !== "FAMILY") {
    redirect("/login");
  }

  let patients: any[] = [];
  let dbError: string | null = null;

  try {
    patients = await prisma.patient.findMany({
      where: { familyId: session.user.id },
      include: {
        medications: true,
        doctor: true,
      },
      orderBy: { createdAt: "desc" },
    });
  } catch (err) {
    console.error("[DASHBOARD_ERROR]", err);
    if (err instanceof Error) {
      if (err.message.includes("Unknown column") || err.message.includes("doesn't exist")) {
        dbError = "Database schema is out of sync. Please run `npx prisma db push` and try again.";
      } else if (err.message.includes("connect") || err.message.includes("ECONNREFUSED")) {
        dbError = "Cannot connect to the database. Please check your DATABASE_URL.";
      } else {
        dbError = `Failed to load patients: ${err.message}`;
      }
    } else {
      dbError = "Failed to load patients. Please try again.";
    }
  }

  const totalPatients = patients.length;
  const activeMedications = patients.reduce(
    (sum, p) => sum + p.medications.length,
    0
  );
  const assignedDoctors = new Set(patients.map((p) => p.doctorId).filter(Boolean)).size;

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-100">
      <Sidebar />
      <main className="p-4 md:ml-64 md:p-8">
        <div className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h1 className="text-2xl font-bold text-zinc-100">
              Family Dashboard
            </h1>
            <p className="mt-1 text-sm text-zinc-400">
              Manage your patients, medications, and doctors.
            </p>
          </div>
          <Link
            href="/dashboard/patients/new"
            className="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-medium text-white transition-colors hover:bg-indigo-500"
          >
            <Plus className="h-4 w-4" />
            Add Patient
          </Link>
        </div>

        <div className="mb-8 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          <StatCard
            title="Total Patients"
            value={totalPatients}
            icon={Users}
          />
          <StatCard
            title="Active Medications"
            value={activeMedications}
            icon={Pill}
          />
          <StatCard
            title="Assigned Doctors"
            value={assignedDoctors}
            icon={Stethoscope}
          />
        </div>

        <h2 className="mb-4 text-lg font-semibold text-zinc-100">Patients</h2>

        {dbError && (
          <div className="mb-6 rounded-lg border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-400">
            <p className="font-medium">Error loading patients:</p>
            <p className="mt-1">{dbError}</p>
          </div>
        )}

        {patients.length === 0 && !dbError ? (
          <div className="rounded-xl border border-zinc-800 bg-zinc-900 p-8 text-center">
            <p className="text-zinc-400">No patients found.</p>
            <Link
              href="/dashboard/patients/new"
              className="mt-4 inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500"
            >
              <Plus className="h-4 w-4" />
              Add your first patient
            </Link>
          </div>
        ) : (
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
            {patients.map((patient) => (
              <div
                key={patient.id}
                className="rounded-xl border border-zinc-800 bg-zinc-900 p-5 transition-colors hover:border-zinc-700"
              >
                <div className="flex items-start justify-between">
                  <div>
                    <h3 className="text-base font-semibold text-zinc-100">
                      {patient.name} {patient.firstName}
                    </h3>
                    <p className="mt-0.5 text-sm text-zinc-400">
                      Age: {calculateAge(patient.dob)} years
                    </p>
                  </div>
                  <span
                    className={`rounded-full border px-2.5 py-0.5 text-xs font-medium ${getStageBadgeClass(
                      patient.alzheimerType
                    )}`}
                  >
                    {patient.alzheimerType}
                  </span>
                </div>

                <div className="mt-4 flex items-center justify-between border-t border-zinc-800 pt-4">
                  <div className="text-xs text-zinc-500">
                    {patient.doctor ? `Dr. ${patient.doctor.name}` : "No doctor assigned"}
                  </div>
                  <PatientActions
                    patientId={patient.id}
                    qrCodeUrl={patient.qrCodeUrl}
                  />
                </div>
              </div>
            ))}
          </div>
        )}
      </main>
    </div>
  );
}

