"use client";

import { useState, useEffect } from "react";
import { Check, Pill } from "lucide-react";
import { isMedTakenToday, markMedAsTaken } from "./MedicationAlert";

interface MedicationCardProps {
  id: string;
  patientId: string;
  drugName: string;
  dosage: string;
  timing: string;
  notes?: string | null;
}

export default function MedicationCard({
  id,
  patientId,
  drugName,
  dosage,
  timing,
  notes,
}: MedicationCardProps) {
  const [isDone, setIsDone] = useState(false);

  useEffect(() => {
    setIsDone(isMedTakenToday(id));
  }, [id]);

  return (
    <button
      onClick={async () => {
        const next = !isDone;
        setIsDone(next);
        if (next) {
          markMedAsTaken(id);
          try {
            const { markMedicationAsTaken } = await import("@/app/actions/patient");
            await markMedicationAsTaken(id, patientId);
          } catch (err) {
            console.error("[MedicationCard] Failed to notify server:", err);
          }
        }
      }}
      className={`flex w-full items-center gap-5 rounded-2xl border-2 p-6 text-left transition-all active:scale-[0.98] ${
        isDone
          ? "border-emerald-500 bg-zinc-900/50 opacity-60"
          : "border-zinc-700 bg-zinc-900 hover:border-zinc-600"
      }`}
      aria-pressed={isDone}
    >
      {/* Large Checkbox */}
      <div
        className={`flex h-16 w-16 flex-shrink-0 items-center justify-center rounded-xl border-3 transition-colors ${
          isDone
            ? "border-emerald-500 bg-emerald-500"
            : "border-zinc-500 bg-transparent"
        }`}
        style={{ borderWidth: "3px" }}
      >
        {isDone && <Check className="h-10 w-10 text-white" strokeWidth={3} />}
      </div>

      {/* Medication Info */}
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-3">
          <Pill
            className={`h-7 w-7 flex-shrink-0 ${
              isDone ? "text-zinc-600" : "text-indigo-400"
            }`}
            strokeWidth={2.5}
          />
          <p
            className={`text-3xl font-bold leading-tight ${
              isDone ? "text-zinc-500 line-through" : "text-white"
            }`}
          >
            {drugName}
          </p>
        </div>
        <p
          className={`mt-1 text-2xl font-medium ${
            isDone ? "text-zinc-600 line-through" : "text-zinc-300"
          }`}
        >
          {dosage}
        </p>
        {notes && (
          <p
            className={`mt-1 text-xl ${
              isDone ? "text-zinc-700 line-through" : "text-zinc-400"
            }`}
          >
            {notes}
          </p>
        )}
      </div>
    </button>
  );
}
