"use client";

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

interface Props { childId: string }

export function AllergyTab({ childId }: Props) {
  const [allergies, setAllergies]           = useState<Allergy[]>([]);
  const [editingAllergy, setEditingAllergy] = useState<Allergy | null>(null);
  const [showAdd, setShowAdd]               = useState(false);
  const [name, setName]                     = useState("");
  const [severity, setSeverity]             = useState("mild");
  const [notes, setNotes]                   = useState("");

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

  const fetchAllergies = () =>
    api.get<{ allergies: Allergy[] }>(`/api/allergies?childId=${childId}`)
      .then(d => setAllergies(d.allergies || []))
      .catch(console.error);

  const save = async () => {
    if (!name) return;
    try {
      if (editingAllergy) {
        await api.patch("/api/allergies", { id: editingAllergy.id, name, severity, notes });
      } else {
        await api.post("/api/allergies", { childId, name, severity, notes });
      }
      fetchAllergies();
    } catch (err) { console.error("Failed to save allergy:", err); }
    reset();
  };

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

  const edit = (a: Allergy) => {
    setEditingAllergy(a);
    setName(a.name);
    setSeverity(a.severity);
    setNotes(a.notes);
    setShowAdd(true);
  };

  const reset = () => {
    setEditingAllergy(null);
    setName("");
    setSeverity("mild");
    setNotes("");
    setShowAdd(false);
  };

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

      {showAdd && (
        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl space-y-3">
          <Input placeholder="Allergy name (e.g., Peanut, Milk)" value={name} onChange={e => setName(e.target.value)} />
          <Select value={severity} onChange={e => setSeverity(e.target.value)}>
            <option value="mild">Mild</option>
            <option value="moderate">Moderate</option>
            <option value="severe">Severe</option>
          </Select>
          <Input placeholder="Notes" value={notes} onChange={e => setNotes(e.target.value)} />
          <div className="flex gap-2">
            <Button fullWidth onClick={save}>{editingAllergy ? "Update" : "Add"}</Button>
            <Button variant="secondary" fullWidth onClick={reset}>Cancel</Button>
          </div>
        </div>
      )}

      {allergies.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 allergies recorded</p>
        </div>
      ) : (
        allergies.map(a => (
          <div key={a.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">{a.name}</div>
                <div className="text-sm text-gray-500 dark:text-gray-400">
                  <span className={a.severity === "severe" ? "text-red-500" : "text-orange-500"}>
                    {a.severity.toUpperCase()}
                  </span>
                  {a.notes && ` · ${a.notes}`}
                </div>
              </div>
              <div className="flex gap-2">
                <button onClick={() => edit(a)} className="p-2 text-gray-400">✏️</button>
                <button onClick={() => remove(a.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">
          + Add Allergy
        </button>
      )}
    </div>
  );
}
