import { redirect } from "next/navigation";
import Link from "next/link";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { Plus, User } from "lucide-react";
import Sidebar from "../_components/Sidebar";
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 PatientsPage() {
  const session = await auth();

  if (!session?.user?.id) {
    redirect("/login");
  }

  if (session.user.role !== "FAMILY") {
    redirect("/login");
  }

  const patients = await prisma.patient.findMany({
    where: { familyId: session.user.id },
    include: {
      medications: true,
      doctor: true,
    },
    orderBy: { createdAt: "desc" },
  });

  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">Patients</h1>
            <p className="mt-1 text-sm text-zinc-400">
              Manage your patients and view their details.
            </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 New Patient
          </Link>
        </div>

        {patients.length === 0 ? (
          <div className="flex flex-col items-center justify-center rounded-xl border border-zinc-800 bg-zinc-900 p-12 text-center">
            <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-zinc-800">
              <User className="h-8 w-8 text-zinc-500" />
            </div>
            <h3 className="text-lg font-semibold text-zinc-100">
              No patients found
            </h3>
            <p className="mt-2 max-w-sm text-sm text-zinc-400">
              You haven&apos;t added any patients yet. Get started by creating
              your first patient profile.
            </p>
            <Link
              href="/dashboard/patients/new"
              className="mt-6 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" />
              Create your first patient
            </Link>
          </div>
        ) : (
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
            {patients.map((patient) => (
              <div
                key={patient.id}
                className="group flex flex-col rounded-xl border border-zinc-800 bg-zinc-900 p-5 transition-all hover:border-zinc-700"
              >
                {/* Card Header */}
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-zinc-800">
                      <User className="h-5 w-5 text-zinc-400" />
                    </div>
                    <div>
                      <h3 className="text-base font-semibold text-zinc-100">
                        {patient.name} {patient.firstName}
                      </h3>
                      <p className="text-xs text-zinc-500">
                        Age: {calculateAge(patient.dob)} years
                      </p>
                    </div>
                  </div>
                  <span
                    className={`rounded-full border px-2.5 py-0.5 text-xs font-medium ${getStageBadgeClass(
                      patient.alzheimerType
                    )}`}
                  >
                    {patient.alzheimerType}
                  </span>
                </div>

                {/* Progress Bar */}
                <div className="mt-4">
                  <div className="mb-1 flex items-center justify-between">
                    <span className="text-xs text-zinc-500">
                      Disease Progression
                    </span>
                    <span className="text-xs font-medium text-zinc-400">
                      {patient.progress}%
                    </span>
                  </div>
                  <div className="h-1.5 w-full overflow-hidden rounded-full bg-zinc-800">
                    <div
                      className="h-full rounded-full bg-indigo-500"
                      style={{ width: `${patient.progress}%` }}
                    />
                  </div>
                </div>

                {/* Doctor Info */}
                <div className="mt-4 border-t border-zinc-800 pt-4">
                  <p className="text-xs text-zinc-500">
                    Assigned Doctor:{" "}
                    <span className="text-zinc-400">
                      {patient.doctor ? `Dr. ${patient.doctor.name}` : "Not assigned"}
                    </span>
                  </p>
                </div>

                {/* Quick Actions */}
                <div className="mt-auto flex items-center justify-end gap-2 border-t border-zinc-800 pt-4">
                  <PatientActions
                    patientId={patient.id}
                    qrCodeUrl={patient.qrCodeUrl}
                  />
                </div>
              </div>
            ))}
          </div>
        )}
      </main>
    </div>
  );
}

