"use client";

import { useState } from "react";
import { formatDistanceToNow } from "date-fns";
import { User, Pill, Activity, ChevronRight } from "lucide-react";
import MedicationHistoryModal from "./MedicationHistoryModal";

interface MedicationLog {
  id: string;
  takenAt: string;
  medicationId: string;
}

interface Medication {
  id: string;
  drugName: string;
  dosage: string;
  timing: string;
  notes: string | null;
  logs: MedicationLog[];
}

interface FamilyContact {
  name: string;
  phone: string | null;
}

interface PatientCardProps {
  patient: {
    id: string;
    name: string;
    firstName: string;
    dob: string;
    alzheimerType: string;
    adherenceRate: number;
    totalMeds: number;
    takenToday: number;
    lastActivity: string | null;
    family: FamilyContact | null;
    medications: Medication[];
  };
}

function calculateAge(dobStr: string): number {
  const dob = new Date(dobStr);
  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-500/10 text-emerald-400 border-emerald-500/20";
  if (lower.includes("middle"))
    return "bg-amber-500/10 text-amber-400 border-amber-500/20";
  if (lower.includes("late"))
    return "bg-rose-500/10 text-rose-400 border-rose-500/20";
  return "bg-white/5 text-zinc-400 border-white/10";
}

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 PatientCard({ patient }: PatientCardProps) {
  const [isModalOpen, setIsModalOpen] = useState(false);

  return (
    <>
      <div className="group relative flex flex-col overflow-hidden rounded-2xl border border-white/10 bg-white/[0.03] p-5 shadow-xl backdrop-blur-xl transition-all hover:border-white/20 hover:bg-white/[0.05]">
        {/* Subtle gradient overlay */}
        <div className="pointer-events-none absolute inset-0 bg-gradient-to-br from-white/[0.02] to-transparent" />

        {/* Card Header */}
        <div className="relative flex items-start justify-between">
          <div className="flex items-center gap-3">
            <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-white/5 ring-1 ring-white/10">
              <User className="h-5 w-5 text-zinc-400" />
            </div>
            <div>
              <h3 className="text-base font-semibold text-zinc-100">
                {patient.firstName} {patient.name}
              </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 backdrop-blur-sm ${getStageBadgeClass(
              patient.alzheimerType
            )}`}
          >
            {patient.alzheimerType}
          </span>
        </div>

        {/* Adherence Rate */}
        <div className="relative mt-5">
          <div className="mb-2 flex items-center justify-between">
            <div className="flex items-center gap-1.5">
              <Pill className="h-3.5 w-3.5 text-zinc-500" />
              <span className="text-xs text-zinc-500">
                Today&apos;s Adherence
              </span>
            </div>
            <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 ring-1 ring-white/5">
            <div
              className={`h-full rounded-full transition-all duration-500 ${getAdherenceColor(
                patient.adherenceRate
              )}`}
              style={{ width: `${patient.adherenceRate}%` }}
            />
          </div>
          <p className="mt-1.5 text-xs text-zinc-600">
            {patient.takenToday} of {patient.totalMeds} medications taken
          </p>
        </div>

        {/* Last Activity */}
        <div className="relative mt-3 flex items-center gap-1.5">
          <Activity className="h-3.5 w-3.5 text-zinc-500" />
          <span className="text-xs text-zinc-500">Last Activity: </span>
          <span className="text-xs text-zinc-400">
            {patient.lastActivity
              ? formatDistanceToNow(new Date(patient.lastActivity), {
                  addSuffix: true,
                })
              : "No activity yet"}
          </span>
        </div>

        {/* Family Contact */}
        {patient.family && (
          <div className="relative mt-2 text-xs text-zinc-600">
            Family: {patient.family.name}
            {patient.family.phone && ` • ${patient.family.phone}`}
          </div>
        )}

        {/* View Details Button */}
        <div className="relative mt-auto border-t border-white/5 pt-4">
          <button
            onClick={() => setIsModalOpen(true)}
            className="flex w-full items-center justify-center gap-2 rounded-xl bg-white/5 px-4 py-2.5 text-sm font-medium text-zinc-300 ring-1 ring-white/10 transition-all hover:bg-white/10 hover:text-white hover:ring-white/20"
          >
            View Details
            <ChevronRight className="h-4 w-4 transition-transform group-hover:translate-x-0.5" />
          </button>
        </div>
      </div>

      <MedicationHistoryModal
        patient={{
          id: patient.id,
          name: patient.name,
          firstName: patient.firstName,
          alzheimerType: patient.alzheimerType,
          adherenceRate: patient.adherenceRate,
          totalMeds: patient.totalMeds,
          takenToday: patient.takenToday,
        }}
        medications={patient.medications}
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
      />
    </>
  );
}

