import { notFound } from "next/navigation";
import Link from "next/link";
import { format } from "date-fns";
import { Sun, Cloud, Moon, Phone, Stethoscope, AlertCircle } from "lucide-react";
import { prisma } from "@/lib/prisma";
import MedicationCard from "./_components/MedicationCard";
import MedicationAlert from "./_components/MedicationAlert";

interface PatientPageProps {
  params: Promise<{ id: string }>;
}

function getTimingCategory(timing: string): "morning" | "afternoon" | "evening" | "other" {
  const lower = timing.toLowerCase();
  const morningKeywords = [
    "morning",
    "am",
    "matin",
    "sobh",
    "صباح",
    "breakfast",
    "petit déjeuner",
  ];
  const afternoonKeywords = [
    "afternoon",
    "noon",
    "midday",
    "lunch",
    "après-midi",
    "zohr",
    "ظهر",
  ];
  const eveningKeywords = [
    "night",
    "pm",
    "evening",
    "soir",
    "lil",
    "ليل",
    "dinner",
    "dîner",
    "bedtime",
    "coucher",
  ];

  if (morningKeywords.some((k) => lower.includes(k))) return "morning";
  if (afternoonKeywords.some((k) => lower.includes(k))) return "afternoon";
  if (eveningKeywords.some((k) => lower.includes(k))) return "evening";
  return "other";
}

export async function generateMetadata({ params }: PatientPageProps) {
  const { id } = await params;
  const patient = await prisma.patient.findUnique({
    where: { id },
    select: { name: true, firstName: true },
  });

  return {
    title: patient
      ? `Welcome, ${patient.firstName} ${patient.name}`
      : "Patient Dashboard",
  };
}

export default async function PatientPage({ params }: PatientPageProps) {
  const { id } = await params;

  const patient = await prisma.patient.findUnique({
    where: { id },
    include: {
      medications: true,
      doctor: true,
      family: {
        select: {
          name: true,
          phone: true,
          relationship: true,
        },
      },
    },
  });

  if (!patient) {
    notFound();
  }

  const today = new Date();
  const todayFormatted = format(today, "EEEE, MMMM do, yyyy");

  const morningMeds = patient.medications.filter(
    (m) => getTimingCategory(m.timing) === "morning"
  );
  const afternoonMeds = patient.medications.filter(
    (m) => getTimingCategory(m.timing) === "afternoon"
  );
  const eveningMeds = patient.medications.filter(
    (m) => getTimingCategory(m.timing) === "evening"
  );
  const otherMeds = patient.medications.filter(
    (m) => getTimingCategory(m.timing) === "other"
  );

  const hasAnyMedications = patient.medications.length > 0;

  return (
    <main className="min-h-screen bg-zinc-950 text-white">
      <div className="mx-auto max-w-2xl px-4 py-10 sm:px-6">
        {/* Medication Alert Overlay */}
        <MedicationAlert
          patientId={id}
          medications={patient.medications.map((m) => ({
            id: m.id,
            drugName: m.drugName,
            dosage: m.dosage,
            timing: m.timing,
          }))}
        />

        {/* Identity / Orientation Section */}
        <section className="mb-12 text-center">
          <h1 className="text-5xl font-extrabold leading-tight tracking-tight sm:text-6xl">
            Welcome back,
          </h1>
          <h2 className="mt-2 text-5xl font-extrabold leading-tight text-indigo-400 sm:text-6xl">
            {patient.firstName} {patient.name}
          </h2>
          <p className="mt-3 text-2xl font-medium text-zinc-400">
            Today is {todayFormatted}
          </p>
        </section>

        {/* Daily Schedule — Medications */}
        <section className="mb-12">
          <h3 className="mb-8 text-center text-4xl font-bold">
            Today&apos;s Medications
          </h3>

          {!hasAnyMedications && (
            <div className="flex flex-col items-center justify-center rounded-2xl border-2 border-zinc-800 bg-zinc-900 p-10 text-center">
              <AlertCircle className="mb-4 h-16 w-16 text-zinc-500" />
              <p className="text-3xl font-semibold text-zinc-300">
                No medications today
              </p>
            </div>
          )}

          {/* Morning */}
          {morningMeds.length > 0 && (
            <div className="mb-10">
              <div className="mb-5 flex items-center gap-4">
                <Sun className="h-12 w-12 text-amber-400" strokeWidth={2.5} />
                <h4 className="text-3xl font-bold text-amber-400">Morning</h4>
              </div>
              <div className="flex flex-col gap-4">
                {morningMeds.map((med) => (
                  <MedicationCard
                    key={med.id}
                    patientId={id}
                    id={med.id}
                    drugName={med.drugName}
                    dosage={med.dosage}
                    timing={med.timing}
                    notes={med.notes}
                  />
                ))}
              </div>
            </div>
          )}

          {/* Afternoon */}
          {afternoonMeds.length > 0 && (
            <div className="mb-10">
              <div className="mb-5 flex items-center gap-4">
                <Cloud className="h-12 w-12 text-sky-400" strokeWidth={2.5} />
                <h4 className="text-3xl font-bold text-sky-400">Afternoon</h4>
              </div>
              <div className="flex flex-col gap-4">
                {afternoonMeds.map((med) => (
                  <MedicationCard
                    key={med.id}
                    patientId={id}
                    id={med.id}
                    drugName={med.drugName}
                    dosage={med.dosage}
                    timing={med.timing}
                    notes={med.notes}
                  />
                ))}
              </div>
            </div>
          )}

          {/* Evening */}
          {eveningMeds.length > 0 && (
            <div className="mb-10">
              <div className="mb-5 flex items-center gap-4">
                <Moon className="h-12 w-12 text-indigo-400" strokeWidth={2.5} />
                <h4 className="text-3xl font-bold text-indigo-400">Evening</h4>
              </div>
              <div className="flex flex-col gap-4">
                {eveningMeds.map((med) => (
                  <MedicationCard
                    key={med.id}
                    patientId={id}
                    id={med.id}
                    drugName={med.drugName}
                    dosage={med.dosage}
                    timing={med.timing}
                    notes={med.notes}
                  />
                ))}
              </div>
            </div>
          )}

          {/* Other */}
          {otherMeds.length > 0 && (
            <div className="mb-10">
              <div className="mb-5 flex items-center gap-4">
                <div className="flex h-12 w-12 items-center justify-center rounded-full bg-zinc-800">
                  <span className="text-2xl font-bold text-zinc-300">?</span>
                </div>
                <h4 className="text-3xl font-bold text-zinc-300">Other</h4>
              </div>
              <div className="flex flex-col gap-4">
                {otherMeds.map((med) => (
                  <MedicationCard
                    key={med.id}
                    patientId={id}
                    id={med.id}
                    drugName={med.drugName}
                    dosage={med.dosage}
                    timing={med.timing}
                    notes={med.notes}
                  />
                ))}
              </div>
            </div>
          )}
        </section>

        {/* Emergency / Family Contact */}
        <section className="mb-12">
          <h3 className="mb-6 text-center text-4xl font-bold">
            Need Help?
          </h3>
          {patient.family?.phone ? (
            <div>
              <Link
                href={`tel:${patient.family.phone}`}
                className="flex w-full items-center justify-center gap-5 rounded-2xl bg-red-600 py-7 text-3xl font-bold text-white transition-colors hover:bg-red-500 active:bg-red-700"
              >
                <Phone className="h-10 w-10" strokeWidth={2.5} />
                Call Family
              </Link>
              <p className="mt-3 text-center text-2xl text-zinc-400">
                Calling: {patient.family.relationship ? `${patient.family.relationship} - ` : ""}
                {patient.family.name}
              </p>
            </div>
          ) : (
            <div className="rounded-2xl border-2 border-zinc-800 bg-zinc-900 p-8 text-center">
              <Phone className="mx-auto mb-3 h-12 w-12 text-zinc-500" />
              <p className="text-2xl text-zinc-400">
                No family phone number available
              </p>
            </div>
          )}
        </section>

        {/* Doctor Info */}
        {patient.doctor && (
          <section className="mb-16 rounded-2xl border-2 border-zinc-800 bg-zinc-900 p-8">
            <div className="mb-4 flex items-center gap-4">
              <Stethoscope
                className="h-10 w-10 text-emerald-400"
                strokeWidth={2.5}
              />
              <h3 className="text-3xl font-bold">Your Doctor</h3>
            </div>
            <p className="text-3xl font-semibold text-white">
              Dr. {patient.doctor.name}
            </p>
            <p className="mt-1 text-2xl text-zinc-400">
              {patient.doctor.specialization}
            </p>
            {patient.doctor.phone && (
              <Link
                href={`tel:${patient.doctor.phone}`}
                className="mt-5 inline-flex items-center gap-3 rounded-xl bg-zinc-800 px-6 py-4 text-2xl font-semibold text-white transition-colors hover:bg-zinc-700"
              >
                <Phone className="h-7 w-7" strokeWidth={2.5} />
                Call Doctor
              </Link>
            )}
          </section>
        )}

        {/* Footer spacer for comfortable scroll end */}
        <div className="h-8" />
      </div>
    </main>
  );
}
