"use client";

import { useEffect, useRef } from "react";
import { format } from "date-fns";
import { X, Pill, Clock, Calendar, Activity } from "lucide-react";

interface MedicationLog {
  id: string;
  takenAt: string;
  medicationId: string;
}

interface Medication {
  id: string;
  drugName: string;
  dosage: string;
  timing: string;
  notes: string | null;
  logs: MedicationLog[];
}

interface PatientData {
  id: string;
  name: string;
  firstName: string;
  alzheimerType: string;
  adherenceRate: number;
  totalMeds: number;
  takenToday: number;
}

interface MedicationHistoryModalProps {
  patient: PatientData;
  medications: Medication[];
  isOpen: boolean;
  onClose: () => void;
}

function getAdherenceColor(rate: number): string {
  if (rate >= 80) return "bg-emerald-500";
  if (rate >= 50) return "bg-amber-500";
  return "bg-rose-500";
}

function getAdherenceTextColor(rate: number): string {
  if (rate >= 80) return "text-emerald-400";
  if (rate >= 50) return "text-amber-400";
  return "text-rose-400";
}

export default function MedicationHistoryModal({
  patient,
  medications,
  isOpen,
  onClose,
}: MedicationHistoryModalProps) {
  const overlayRef = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!isOpen) return;

    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };

    const handleClickOutside = (e: MouseEvent) => {
      if (
        overlayRef.current === e.target &&
        !contentRef.current?.contains(e.target as Node)
      ) {
        onClose();
      }
    };

    document.addEventListener("keydown", handleEscape);
    document.addEventListener("mousedown", handleClickOutside);
    document.body.style.overflow = "hidden";

    return () => {
      document.removeEventListener("keydown", handleEscape);
      document.removeEventListener("mousedown", handleClickOutside);
      document.body.style.overflow = "";
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const allLogs = medications
    .flatMap((med) =>
      med.logs.map((log) => ({
        ...log,
        drugName: med.drugName,
        dosage: med.dosage,
        timing: med.timing,
      }))
    )
    .sort(
      (a, b) =>
        new Date(b.takenAt).getTime() - new Date(a.takenAt).getTime()
    );

  const medicationsWithLogs = medications.filter((med) => med.logs.length > 0);
  const medicationsWithoutLogs = medications.filter(
    (med) => med.logs.length === 0
  );

  return (
    <div
      ref={overlayRef}
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
    >
      <div
        ref={contentRef}
        className="relative w-full max-w-2xl max-h-[85vh] overflow-hidden rounded-2xl border border-white/10 bg-zinc-900/80 backdrop-blur-xl shadow-2xl"
      >
        {/* Header */}
        <div className="flex items-center justify-between border-b border-white/10 px-6 py-4">
          <div>
            <h2 className="text-lg font-bold text-zinc-100">
              {patient.firstName} {patient.name}
            </h2>
            <p className="text-xs text-zinc-500">
              Medication History • {patient.alzheimerType}
            </p>
          </div>
          <button
            onClick={onClose}
            aria-label="Close modal"
            className="flex h-8 w-8 items-center justify-center rounded-lg bg-white/5 text-zinc-400 transition-colors hover:bg-white/10 hover:text-zinc-200"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* Scrollable Content */}
        <div className="overflow-y-auto max-h-[calc(85vh-80px)] p-6">
          {/* Summary Stats */}
          <div className="mb-6 grid grid-cols-3 gap-3">
            <div className="rounded-xl border border-white/5 bg-white/5 p-3 text-center backdrop-blur-sm">
              <Activity className="mx-auto mb-1 h-4 w-4 text-indigo-400" />
              <p className={`text-lg font-bold ${getAdherenceTextColor(patient.adherenceRate)}`}>
                {patient.adherenceRate}%
              </p>
              <p className="text-[10px] uppercase tracking-wide text-zinc-500">Adherence</p>
            </div>
            <div className="rounded-xl border border-white/5 bg-white/5 p-3 text-center backdrop-blur-sm">
              <Pill className="mx-auto mb-1 h-4 w-4 text-sky-400" />
              <p className="text-lg font-bold text-zinc-100">
                {patient.takenToday}/{patient.totalMeds}
              </p>
              <p className="text-[10px] uppercase tracking-wide text-zinc-500">Today</p>
            </div>
            <div className="rounded-xl border border-white/5 bg-white/5 p-3 text-center backdrop-blur-sm">
              <Calendar className="mx-auto mb-1 h-4 w-4 text-emerald-400" />
              <p className="text-lg font-bold text-zinc-100">
                {allLogs.length}
              </p>
              <p className="text-[10px] uppercase tracking-wide text-zinc-500">Total Logs</p>
            </div>
          </div>

          {/* Progress Bar */}
          <div className="mb-6">
            <div className="mb-1.5 flex items-center justify-between">
              <span className="text-xs text-zinc-500">Today&apos;s Progress</span>
              <span className={`text-xs font-bold ${getAdherenceTextColor(patient.adherenceRate)}`}>
                {patient.adherenceRate}%
              </span>
            </div>
            <div className="h-2 w-full overflow-hidden rounded-full bg-white/5">
              <div
                className={`h-full rounded-full transition-all ${getAdherenceColor(
                  patient.adherenceRate
                )}`}
                style={{ width: `${patient.adherenceRate}%` }}
              />
            </div>
          </div>

          {/* Recent Logs */}
          {allLogs.length > 0 && (
            <div className="mb-6">
              <h3 className="mb-3 text-sm font-semibold text-zinc-300">
                Recent Activity
              </h3>
              <div className="space-y-2">
                {allLogs.slice(0, 10).map((log) => (
                  <div
                    key={log.id}
                    className="flex items-center gap-3 rounded-lg border border-white/5 bg-white/[0.03] p-3 backdrop-blur-sm"
                  >
                    <div className="flex h-8 w-8 items-center justify-center rounded-full bg-emerald-500/10">
                      <Pill className="h-3.5 w-3.5 text-emerald-400" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-zinc-200 truncate">
                        {log.drugName}
                      </p>
                      <p className="text-xs text-zinc-500">
                        {log.dosage} • {log.timing}
                      </p>
                    </div>
                    <div className="flex items-center gap-1 text-xs text-zinc-500 flex-shrink-0">
                      <Clock className="h-3 w-3" />
                      {format(new Date(log.takenAt), "MMM d, h:mm a")}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Medications Breakdown */}
          <div>
            <h3 className="mb-3 text-sm font-semibold text-zinc-300">
              Medications
            </h3>

            {medicationsWithLogs.length > 0 && (
              <div className="mb-4 space-y-2">
                {medicationsWithLogs.map((med) => (
                  <div
                    key={med.id}
                    className="rounded-lg border border-white/5 bg-white/[0.03] p-3 backdrop-blur-sm"
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Pill className="h-3.5 w-3.5 text-indigo-400" />
                        <span className="text-sm font-medium text-zinc-200">
                          {med.drugName}
                        </span>
                      </div>
                      <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] font-medium text-emerald-400">
                        {med.logs.length} taken
                      </span>
                    </div>
                    <p className="mt-1 text-xs text-zinc-500">
                      {med.dosage} • {med.timing}
                    </p>
                    {med.notes && (
                      <p className="mt-1 text-xs text-zinc-600">{med.notes}</p>
                    )}
                    <div className="mt-2 flex flex-wrap gap-1">
                      {med.logs.slice(0, 5).map((log, idx) => (
                        <span
                          key={log.id}
                          className="rounded bg-white/5 px-1.5 py-0.5 text-[10px] text-zinc-500"
                        >
                          {format(new Date(log.takenAt), "MMM d")}
                        </span>
                      ))}
                      {med.logs.length > 5 && (
                        <span className="rounded bg-white/5 px-1.5 py-0.5 text-[10px] text-zinc-600">
                          +{med.logs.length - 5} more
                        </span>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}

            {medicationsWithoutLogs.length > 0 && (
              <div className="space-y-2">
                <p className="text-xs text-zinc-600">Never taken:</p>
                {medicationsWithoutLogs.map((med) => (
                  <div
                    key={med.id}
                    className="flex items-center justify-between rounded-lg border border-white/5 bg-white/[0.02] p-3 opacity-60"
                  >
                    <div className="flex items-center gap-2">
                      <Pill className="h-3.5 w-3.5 text-zinc-600" />
                      <span className="text-sm text-zinc-500">
                        {med.drugName}
                      </span>
                    </div>
                    <span className="text-xs text-zinc-600">
                      {med.dosage}
                    </span>
                  </div>
                ))}
              </div>
            )}

            {medications.length === 0 && (
              <p className="text-sm text-zinc-600">
                No medications assigned to this patient.
              </p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

