"use client";

import { useState, useEffect } from "react";
import { Button, Input } from "@/components/ui";
import { api } from "@/lib/api";
import type { Illness } from "@/types";

interface Props { childId: string }

export function IllnessTab({ childId }: Props) {
  const [illnesses, setIllnesses]           = useState<Illness[]>([]);
  const [editingIllness, setEditingIllness] = useState<Illness | null>(null);
  const [showAdd, setShowAdd]               = useState(false);
  const [name, setName]                     = useState("");
  const [startDate, setStartDate]           = useState("");
  const [endDate, setEndDate]               = useState("");
  const [notes, setNotes]                   = useState("");

  useEffect(() => { fetchIllnesses(); }, [childId]);

  const fetchIllnesses = () =>
    api.get<{ illnesses: Illness[] }>(`/api/illnesses?childId=${childId}`)
      .then(d => setIllnesses(d.illnesses || []))
      .catch(console.error);

  const save = async () => {
    if (!name) return;
    try {
      if (editingIllness) {
        await api.patch("/api/illnesses", { id: editingIllness.id, name, startDate, endDate, notes });
      } else {
        await api.post("/api/illnesses", { childId, name, startDate, endDate, notes });
      }
      fetchIllnesses();
    } catch (err) { console.error("Failed to save illness:", err); }
    reset();
  };

  const remove = async (id: string) => {
    try {
      await api.delete(`/api/illnesses?id=${id}`);
      fetchIllnesses();
    } catch (err) { console.error("Failed to delete illness:", err); }
  };

  const edit = (ill: Illness) => {
    setEditingIllness(ill);
    setName(ill.name);
    setStartDate(ill.startDate);
    setEndDate(ill.endDate || "");
    setNotes(ill.notes);
    setShowAdd(true);
  };

  const reset = () => {
    setEditingIllness(null);
    setName("");
    setStartDate("");
    setEndDate("");
    setNotes("");
    setShowAdd(false);
  };

  return (
    <div className="space-y-2">
      <h2 className="font-semibold mb-3">Illness Log</h2>

      {showAdd && (
        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl space-y-3">
          <Input placeholder="Illness (e.g., Cold, Fever, Flu)" value={name} onChange={e => setName(e.target.value)} />
          <div className="grid grid-cols-2 gap-2">
            <Input type="date" value={startDate} onChange={e => setStartDate(e.target.value)} />
            <Input type="date" value={endDate} onChange={e => setEndDate(e.target.value)} />
          </div>
          <Input placeholder="Notes" value={notes} onChange={e => setNotes(e.target.value)} />
          <div className="flex gap-2">
            <Button fullWidth onClick={save}>{editingIllness ? "Update" : "Add"}</Button>
            <Button variant="secondary" fullWidth onClick={reset}>Cancel</Button>
          </div>
        </div>
      )}

      {illnesses.length === 0 && !showAdd ? (
        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl">
          <p className="text-gray-500 dark:text-gray-400">No illnesses recorded</p>
        </div>
      ) : (
        illnesses.map(ill => (
          <div key={ill.id} className="p-4 bg-white dark:bg-gray-800 rounded-xl">
            <div className="flex items-center justify-between">
              <div className="flex-1">
                <div className="font-medium">{ill.name}</div>
                <div className="text-sm text-gray-500 dark:text-gray-400">
                  {new Date(ill.startDate).toLocaleDateString()}
                  {ill.endDate && ` - ${new Date(ill.endDate).toLocaleDateString()}`}
                  {ill.notes && ` · ${ill.notes}`}
                </div>
              </div>
              <div className="flex gap-2">
                <button onClick={() => edit(ill)} className="p-2 text-gray-400">✏️</button>
                <button onClick={() => remove(ill.id)} className="p-2 text-red-400">🗑️</button>
              </div>
            </div>
          </div>
        ))
      )}

      {!showAdd && (
        <button onClick={() => setShowAdd(true)} className="w-full p-4 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl text-gray-500 dark:text-gray-400">
          + Log Illness
        </button>
      )}
    </div>
  );
}
