import { redirect } from "next/navigation";
import Link from "next/link";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { Users, Activity, Pill, Plus, User } from "lucide-react";
import Sidebar from "../_components/Sidebar";
import PatientCard from "./_components/PatientCard";

export default async function DoctorDashboardPage() {
  const session = await auth();

  if (!session?.user?.id) {
    redirect("/login");
  }

  if (session.user.role !== "DOCTOR") {
    redirect("/dashboard");
  }

  // Find the Doctor record associated with this user
  const doctor = await prisma.doctor.findUnique({
    where: { userId: session.user.id },
  });

  if (!doctor) {
    return (
      <div className="min-h-screen bg-zinc-950 text-zinc-100">
        <Sidebar />
        <main className="flex min-h-screen items-center justify-center p-4 md:ml-64">
          <div className="max-w-md rounded-2xl border border-white/10 bg-white/[0.03] p-8 text-center shadow-xl backdrop-blur-xl">
            <h1 className="text-xl font-bold text-zinc-100">
              Doctor Profile Not Found
            </h1>
            <p className="mt-2 text-sm text-zinc-400">
              Your account is not linked to a doctor profile. Please contact
              support.
            </p>
          </div>
        </main>
      </div>
    );
  }

  // Fetch all patients assigned to this doctor
  const patients = await prisma.patient.findMany({
    where: { doctorId: doctor.id },
    include: {
      medications: {
        include: {
          logs: {
            orderBy: { takenAt: "desc" },
          },
        },
      },
      family: {
        select: {
          name: true,
          phone: true,
        },
      },
    },
    orderBy: { createdAt: "desc" },
  });

  const totalPatients = patients.length;
  const totalMedications = patients.reduce(
    (sum, p) => sum + p.medications.length,
    0
  );

  // Calculate average adherence rate across all patients
  let totalAdherence = 0;
  let patientsWithMeds = 0;

  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);

  const patientsWithStats = patients.map((patient) => {
    const totalMeds = patient.medications.length;
    const takenToday = patient.medications.filter((med) =>
      med.logs.some(
        (log) => log.takenAt >= today && log.takenAt < tomorrow
      )
    ).length;

    const adherenceRate =
      totalMeds > 0 ? Math.round((takenToday / totalMeds) * 100) : 0;

    if (totalMeds > 0) {
      totalAdherence += adherenceRate;
      patientsWithMeds++;
    }

    // Find last activity (most recent medication log)
    const allLogs = patient.medications.flatMap((m) => m.logs);
    const lastLog = allLogs.sort(
      (a, b) =>
        new Date(b.takenAt).getTime() - new Date(a.takenAt).getTime()
    )[0];

    return {
      id: patient.id,
      name: patient.name,
      firstName: patient.firstName,
      dob: patient.dob.toISOString(),
      alzheimerType: patient.alzheimerType,
      adherenceRate,
      totalMeds,
      takenToday,
      lastActivity: lastLog ? lastLog.takenAt.toISOString() : null,
      family: patient.family,
      medications: patient.medications.map((med) => ({
        id: med.id,
        drugName: med.drugName,
        dosage: med.dosage,
        timing: med.timing,
        notes: med.notes,
        logs: med.logs.map((log) => ({
          id: log.id,
          takenAt: log.takenAt.toISOString(),
          medicationId: log.medicationId,
        })),
      })),
    };
  });

  const averageAdherence =
    patientsWithMeds > 0 ? Math.round(totalAdherence / patientsWithMeds) : 0;

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-100">
      <Sidebar />
      <main className="p-4 md:ml-64 md:p-8">
        {/* Welcome Header */}
        <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">
              Welcome, Dr. {doctor.name}
            </h1>
            <p className="mt-1 text-sm text-zinc-400">
              {doctor.specialization} • Manage your patients and monitor
              medication adherence.
            </p>
          </div>
          <Link
            href="/dashboard/patients/new"
            className="inline-flex items-center gap-2 rounded-xl bg-indigo-600 px-5 py-2.5 text-sm font-medium text-white shadow-lg shadow-indigo-500/20 transition-all hover:bg-indigo-500 hover:shadow-indigo-500/30"
          >
            <Plus className="h-4 w-4" />
            Add New Patient
          </Link>
        </div>

        {/* Stats Grid — Glassmorphism */}
        <div className="mb-8 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          <div className="rounded-2xl border border-white/10 bg-white/[0.03] p-6 shadow-xl backdrop-blur-xl">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-zinc-400">Total Patients</p>
                <p className="mt-2 text-3xl font-bold text-zinc-100">{totalPatients}</p>
              </div>
              <div className="rounded-xl bg-white/5 p-3 ring-1 ring-white/10">
                <Users className="h-6 w-6 text-indigo-400" />
              </div>
            </div>
          </div>

          <div className="rounded-2xl border border-white/10 bg-white/[0.03] p-6 shadow-xl backdrop-blur-xl">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-zinc-400">Total Medications</p>
                <p className="mt-2 text-3xl font-bold text-zinc-100">{totalMedications}</p>
              </div>
              <div className="rounded-xl bg-white/5 p-3 ring-1 ring-white/10">
                <Pill className="h-6 w-6 text-sky-400" />
              </div>
            </div>
          </div>

          <div className="rounded-2xl border border-white/10 bg-white/[0.03] p-6 shadow-xl backdrop-blur-xl">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-zinc-400">Avg. Adherence Rate</p>
                <p className="mt-2 text-3xl font-bold text-zinc-100">
                  {averageAdherence}%
                </p>
              </div>
              <div className="rounded-xl bg-white/5 p-3 ring-1 ring-white/10">
                <Activity className="h-6 w-6 text-emerald-400" />
              </div>
            </div>
          </div>
        </div>

        {/* Patients Section */}
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-lg font-semibold text-zinc-100">Your Patients</h2>
          <span className="text-sm text-zinc-500">
            {totalPatients} patient{totalPatients !== 1 ? "s" : ""}
          </span>
        </div>

        {patientsWithStats.length === 0 ? (
          <div className="flex flex-col items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] p-12 text-center shadow-xl backdrop-blur-xl">
            <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-white/5 ring-1 ring-white/10">
              <User className="h-8 w-8 text-zinc-500" />
            </div>
            <h3 className="text-lg font-semibold text-zinc-100">
              No patients assigned
            </h3>
            <p className="mt-2 max-w-sm text-sm text-zinc-400">
              You don&apos;t have any patients assigned yet. Patients can be
              added by family members or you can add them directly.
            </p>
            <Link
              href="/dashboard/patients/new"
              className="mt-6 inline-flex items-center gap-2 rounded-xl bg-indigo-600 px-5 py-2.5 text-sm font-medium text-white shadow-lg shadow-indigo-500/20 transition-all hover:bg-indigo-500 hover:shadow-indigo-500/30"
            >
              <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">
            {patientsWithStats.map((patient) => (
              <PatientCard key={patient.id} patient={patient} />
            ))}
          </div>
        )}
      </main>
    </div>
  );
}

