"use client";

import { useState, useEffect } from "react";
import { TabBar } from "@/components/TabBar";
import { api } from "@/lib/api";
import type { Vaccination } from "@/types";

interface Props {
  childId: string;
  birthDate: string;
}

type VaccineStatus = "upcoming" | "completed" | "overdue";

const IAP_SCHEDULE = [
  { name: "BCG", weeks: 0 },
  { name: "OPV-0", weeks: 0 },
  { name: "HepB-1", weeks: 0 },
  { name: "OPV-1", weeks: 6 },
  { name: "Pentavalent-1", weeks: 6 },
  { name: "PCV-1", weeks: 6 },
  { name: "Rota-1", weeks: 6 },
  { name: "OPV-2", weeks: 10 },
  { name: "Pentavalent-2", weeks: 10 },
  { name: "PCV-2", weeks: 10 },
  { name: "Rota-2", weeks: 10 },
  { name: "OPV-3", weeks: 14 },
  { name: "Pentavalent-3", weeks: 14 },
  { name: "PCV-3", weeks: 14 },
  { name: "Rota-3", weeks: 14 },
  { name: "MR-1", weeks: 48 },
  { name: "JE-1", weeks: 48 },
  { name: "Vitamin A-1", weeks: 48 },
  { name: "OPV-4", weeks: 48 },
  { name: "MR-2", weeks: 96 },
  { name: "JE-2", weeks: 96 },
  { name: "DPT-Booster-1", weeks: 96 },
  { name: "Vitamin A-2", weeks: 96 },
  { name: "OPV-5", weeks: 96 },
  { name: "DPT-Booster-2", weeks: 208 },
  { name: "Td", weeks: 208 },
];

function calculateDueDate(birthDate: string, weeks: number): string {
  const d = new Date(birthDate);
  d.setDate(d.getDate() + weeks * 7);
  return d.toISOString().split("T")[0];
}

const STATUS_TABS = [
  { value: "upcoming",  label: "" },
  { value: "completed", label: "" },
  { value: "overdue",   label: "" },
];

export function VaccineTab({ childId, birthDate }: Props) {
  const [vaccinations, setVaccinations] = useState<Vaccination[]>([]);
  const [loading, setLoading]           = useState(true);
  const [vaccineTab, setVaccineTab]     = useState<VaccineStatus>("upcoming");
  const [showAddDate, setShowAddDate]   = useState<string | null>(null);
  const [givenDate, setGivenDate]       = useState("");

  useEffect(() => {
    api.get<{ vaccinations: Vaccination[] }>(`/api/vaccinations?childId=${childId}`)
      .then(d => setVaccinations(d.vaccinations || []))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [childId]);

  const isGiven = (name: string) => vaccinations.some(v => v.vaccine_name === name && v.status === "given");
  const getGivenDate = (name: string) => vaccinations.find(v => v.vaccine_name === name && v.status === "given")?.given_date;

  const todayStr = new Date().toISOString().split("T")[0];

  const getVaccineStatus = (name: string): VaccineStatus => {
    const due = calculateDueDate(birthDate, IAP_SCHEDULE.find(v => v.name === name)?.weeks ?? 0);
    if (isGiven(name)) return "completed";
    if (due < todayStr)  return "overdue";
    return "upcoming";
  };

  const getByStatus = (status: VaccineStatus) =>
    IAP_SCHEDULE.filter(v => {
      const due = calculateDueDate(birthDate, v.weeks);
      if (status === "completed") return isGiven(v.name);
      if (status === "overdue")   return !isGiven(v.name) && due < todayStr;
      return !isGiven(v.name) && due >= todayStr;
    }).sort((a, b) => a.weeks - b.weeks);

  const handleMarkGiven = async (vaccineName: string) => {
    const due = calculateDueDate(birthDate, IAP_SCHEDULE.find(v => v.name === vaccineName)?.weeks ?? 0);
    const dateToSave = givenDate || todayStr;
    try {
      await api.post("/api/vaccinations", { childId, vaccineName, scheduledDate: due, givenDate: dateToSave, status: "given" });
      setVaccinations(prev => [...prev, { vaccine_name: vaccineName, given_date: dateToSave, status: "given" }]);
    } catch (err) {
      console.error("Failed to mark given:", err);
    }
    setShowAddDate(null);
    setGivenDate("");
  };

  const counts = {
    upcoming:  getByStatus("upcoming").length,
    completed: getByStatus("completed").length,
    overdue:   getByStatus("overdue").length,
  };

  const statusTabs = STATUS_TABS.map(t => ({
    value: t.value,
    label: `${t.value.charAt(0).toUpperCase() + t.value.slice(1)} (${counts[t.value as VaccineStatus]})`,
  }));

  return (
    <div className="space-y-2">
      <TabBar tabs={statusTabs} value={vaccineTab} onChange={v => setVaccineTab(v as VaccineStatus)} danger="overdue" />

      <h2 className="font-semibold mt-2">IAP Schedule</h2>

      {loading ? (
        <p className="text-gray-500">Loading...</p>
      ) : (
        getByStatus(vaccineTab).map(vaccine => {
          const due = calculateDueDate(birthDate, vaccine.weeks);
          const status = getVaccineStatus(vaccine.name);
          const actualDate = getGivenDate(vaccine.name);
          const daysOverdue = status === "overdue"
            ? Math.floor((Date.now() - new Date(due).getTime()) / 86_400_000)
            : 0;

          return (
            <div
              key={vaccine.name}
              className={`p-4 bg-white dark:bg-gray-800 rounded-xl ${status === "completed" ? "opacity-60" : ""} ${status === "overdue" ? "border-l-4 border-red-500" : ""}`}
            >
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <div className="font-medium">{vaccine.name}</div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">
                    Due: {new Date(due).toLocaleDateString()}
                    {actualDate && ` · Given: ${new Date(actualDate).toLocaleDateString()}`}
                  </div>
                  {status === "overdue" && (
                    <div className="text-red-500 text-sm font-medium">{daysOverdue} days overdue</div>
                  )}
                </div>

                {isGiven(vaccine.name) ? (
                  <span className="text-green-500">✓</span>
                ) : showAddDate === vaccine.name ? (
                  <div className="flex gap-2">
                    <input
                      type="date"
                      value={givenDate}
                      onChange={e => setGivenDate(e.target.value)}
                      className="p-1 text-sm border dark:border-gray-600 rounded dark:bg-gray-700 dark:text-white"
                    />
                    <button onClick={() => handleMarkGiven(vaccine.name)} className="px-3 py-1 bg-rose-400 text-white rounded-lg text-sm">✓</button>
                    <button onClick={() => { setShowAddDate(null); setGivenDate(""); }} className="px-2 py-1 text-gray-400">✕</button>
                  </div>
                ) : (
                  <button onClick={() => setShowAddDate(vaccine.name)} className="px-4 py-2 bg-rose-400 text-white rounded-lg text-sm">
                    Mark Given
                  </button>
                )}
              </div>
            </div>
          );
        })
      )}
    </div>
  );
}
