import { useState } from "react";
import { X, Save, Plus, Star, Loader2 } from "lucide-react";
import type { Pet, MedicalAlert, CoatType, AlertSeverity } from "@groombook/types";

const COAT_TYPES: CoatType[] = ["double", "wire", "curly", "smooth", "long", "hairless"];
const SEVERITY_OPTIONS: AlertSeverity[] = ["low", "medium", "high"];
const SIZE_OPTIONS = ["small", "medium", "large", "xlarge"] as const;
type SizeOption = typeof SIZE_OPTIONS[number];

interface Props {
  pet?: Pet;
  onSave: (pet: Pet) => void | Promise<void>;
  onCancel: () => void;
  saving?: boolean;
  saveError?: string | null;
}

function newAlert(): Omit<MedicalAlert, "id"> {
  return { type: "", description: "", severity: "low" };
}

export function PetForm({ pet, onSave, onCancel, saving, saveError }: Props) {
  const [name, setName] = useState(pet?.name ?? "");
  const [breed, setBreed] = useState(pet?.breed ?? "");
  const [weight, setWeight] = useState(pet?.weightKg ?? 0);
  const [notes, setNotes] = useState(pet?.healthAlerts ?? "");
  const [coatType, setCoatType] = useState<CoatType | "">((pet?.coatType as CoatType) ?? "");
  const [petSizeCategory, setPetSizeCategory] = useState<SizeOption | "">(pet?.petSizeCategory as SizeOption ?? "");
  const [preferredCuts, setPreferredCuts] = useState<string[]>(pet?.preferredCuts ?? []);
  const [cutInput, setCutInput] = useState("");
  const [alerts, setAlerts] = useState<Omit<MedicalAlert, "id">[]>(
    pet?.medicalAlerts?.map((alert: MedicalAlert) => ({ type: alert.type, description: alert.description, severity: alert.severity })) ?? []
  );
  const [alertErrors, setAlertErrors] = useState<Record<number, string>>({});

  function addAlert() {
    setAlerts(prev => [...prev, newAlert()]);
  }

  function updateAlert(idx: number, field: keyof Omit<MedicalAlert, "id">, value: string) {
    setAlerts(prev => prev.map((a, i) => i === idx ? { ...a, [field]: value } : a));
    setAlertErrors(prev => { const e = { ...prev }; delete e[idx]; return e; });
  }

  function removeAlert(idx: number) {
    setAlerts(prev => prev.filter((_, i) => i !== idx));
    setAlertErrors(prev => { const e = { ...prev }; delete e[idx]; return e; });
  }

  function addCut() {
    const trimmed = cutInput.trim();
    if (trimmed && !preferredCuts.includes(trimmed)) {
      setPreferredCuts(prev => [...prev, trimmed]);
    }
    setCutInput("");
  }

  function removeCut(cut: string) {
    setPreferredCuts(prev => prev.filter(c => c !== cut));
  }

  function handleCutKey(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Enter") { e.preventDefault(); addCut(); }
  }

  function validateAlerts(): boolean {
    const errors: Record<number, string> = {};
    alerts.forEach((a, i) => {
      if (!a.type.trim()) errors[i] = "Type is required";
      else if (a.severity === "medium" && !a.description.trim()) errors[i] = "Description required at medium/high severity";
    });
    setAlertErrors(errors);
    return Object.keys(errors).length === 0;
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!pet) return;
    if (!handleCutKey) {} // noop reference
    if (alerts.length > 0 && !validateAlerts()) return;

    const savedPet: Pet = {
      ...pet,
      name,
      breed: breed || null,
      weightKg: weight || null,
      healthAlerts: notes,
      coatType: coatType || null,
      petSizeCategory: petSizeCategory || null,
      preferredCuts,
      medicalAlerts: alerts.map((a, i) => ({ ...a, id: pet.medicalAlerts?.[i]?.id ?? crypto.randomUUID() })),
    };
    onSave(savedPet);
  }

  const temperamentScore = pet?.temperamentScore;
  const temperamentFlags = pet?.temperamentFlags ?? [];

  return (
    <div className="bg-white rounded-2xl border border-stone-200 p-6 shadow-sm">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-lg font-semibold text-stone-800">{pet?.id ? "Edit Pet" : "Add Pet"}</h2>
        <button onClick={onCancel} className="p-2 hover:bg-stone-50 rounded-lg">
          <X size={16} className="text-stone-400" />
        </button>
      </div>
      <form onSubmit={handleSubmit} className="space-y-6">

        {/* Basic Info */}
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-stone-600 mb-1">Name *</label>
            <input
              type="text"
              value={name}
              onChange={e => setName(e.target.value)}
              required
              className="w-full border border-stone-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-(--color-accent)"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-stone-600 mb-1">Breed</label>
            <input
              type="text"
              value={breed}
              onChange={e => setBreed(e.target.value)}
              className="w-full border border-stone-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-(--color-accent)"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-stone-600 mb-1">Weight (kg)</label>
            <input
              type="number"
              value={weight}
              onChange={e => setWeight(Number(e.target.value))}
              min="0"
              step="0.1"
              className="w-full border border-stone-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-(--color-accent)"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-stone-600 mb-1">Notes</label>
            <textarea
              value={notes}
              onChange={e => setNotes(e.target.value)}
              rows={3}
              className="w-full border border-stone-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-(--color-accent)"
            />
          </div>
        </div>

        {/* Coat Type */}
        <div>
          <label htmlFor="coat-type" className="block text-sm font-medium text-stone-600 mb-1">Coat Type</label>
          <select
            id="coat-type"
            value={coatType}
            onChange={e => setCoatType(e.target.value as CoatType)}
            className="w-full border border-stone-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-(--color-accent) bg-white"
          >
            <option value="">Select coat type</option>
            {COAT_TYPES.map(ct => (
              <option key={ct} value={ct}>{ct.charAt(0).toUpperCase() + ct.slice(1)}</option>
            ))}
          </select>
        </div>

        {/* Size Category */}
        <div>
          <label htmlFor="size-category" className="block text-sm font-medium text-stone-600 mb-1">Size Category</label>
          <select
            id="size-category"
            value={petSizeCategory}
            onChange={e => setPetSizeCategory(e.target.value as SizeOption)}
            className="w-full border border-stone-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-(--color-accent) bg-white"
          >
            <option value="">Select size</option>
            {SIZE_OPTIONS.map(s => (
              <option key={s} value={s}>{s.charAt(0).toUpperCase() + s.slice(1)}</option>
            ))}
          </select>
        </div>

        {/* Temperament (read-only) */}
        {(temperamentScore != null || temperamentFlags.length > 0) && (
          <div className="bg-stone-50 rounded-xl p-4 space-y-2">
            <label className="block text-sm font-medium text-stone-500 mb-1">Temperament</label>
            {temperamentScore != null && (
              <div className="flex items-center gap-1">
                {[1, 2, 3, 4, 5].map(s => (
                  <Star
                    key={s}
                    size={14}
                    className={s <= temperamentScore ? "text-amber-400 fill-amber-400" : "text-stone-300"}
                  />
                ))}
                <span className="ml-1 text-xs text-stone-500">({temperamentScore}/5)</span>
              </div>
            )}
            {temperamentFlags.length > 0 && (
              <div className="flex flex-wrap gap-1">
                {temperamentFlags.map(flag => (
                  <span key={flag} className="inline-flex items-center px-2 py-0.5 rounded-full bg-amber-100 text-amber-700 text-xs">{flag}</span>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Medical Alerts */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <label className="block text-sm font-medium text-stone-600">Medical Alerts</label>
            <button
              type="button"
              onClick={addAlert}
              className="flex items-center gap-1 text-xs text-(--color-accent-dark) font-medium hover:underline"
            >
              <Plus size={12} /> Add Alert
            </button>
          </div>
          <div className="space-y-3">
            {alerts.map((alert, idx) => (
              <div key={idx} className="border border-stone-200 rounded-lg p-3 space-y-2">
                <div className="flex items-start gap-2">
                  <div className="flex-1 space-y-2">
                    <div className="flex gap-2">
                      <input
                        type="text"
                        placeholder="Alert type (e.g. Allergic to chicken)"
                        value={alert.type}
                        onChange={e => updateAlert(idx, "type", e.target.value)}
                        className="flex-1 border border-stone-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-(--color-accent)"
                      />
                      <select
                        value={alert.severity}
                        onChange={e => updateAlert(idx, "severity", e.target.value as AlertSeverity)}
                        className="border border-stone-200 rounded-lg px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-(--color-accent) bg-white"
                      >
                        {SEVERITY_OPTIONS.map(sev => (
                          <option key={sev} value={sev}>{sev.charAt(0).toUpperCase() + sev.slice(1)}</option>
                        ))}
                      </select>
                    </div>
                    <textarea
                      placeholder="Description (optional)"
                      value={alert.description}
                      onChange={e => updateAlert(idx, "description", e.target.value)}
                      rows={2}
                      className="w-full border border-stone-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-(--color-accent)"
                    />
                    {alertErrors[idx] && (
                      <p className="text-xs text-red-500">{alertErrors[idx]}</p>
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={() => removeAlert(idx)}
                    className="p-1 hover:bg-stone-100 rounded text-stone-400 mt-0.5"
                  >
                    <X size={14} />
                  </button>
                </div>
              </div>
            ))}
            {alerts.length === 0 && (
              <p className="text-sm text-stone-400">No medical alerts on file.</p>
            )}
          </div>
        </div>

        {/* Preferred Cuts */}
        <div>
          <label className="block text-sm font-medium text-stone-600 mb-1">Preferred Cuts</label>
          <div className="flex gap-2 mb-2">
            <input
              type="text"
              value={cutInput}
              onChange={e => setCutInput(e.target.value)}
              onKeyDown={handleCutKey}
              placeholder="Type a cut name and press Enter"
              className="flex-1 border border-stone-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-(--color-accent)"
            />
            <button
              type="button"
              onClick={addCut}
              aria-label="Add"
              className="px-3 py-2 border border border-stone-200 rounded-lg text-sm text-stone-600 hover:bg-stone-50"
            >
              <Plus size={14} />
            </button>
          </div>
          <div className="flex flex-wrap gap-1">
            {preferredCuts.map(cut => (
              <span key={cut} className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-stone-100 text-stone-700 text-xs">
                {cut}
                <button type="button" onClick={() => removeCut(cut)} className="hover:text-red-500">
                  <X size={10} />
                </button>
              </span>
            ))}
            {preferredCuts.length === 0 && <span className="text-xs text-stone-400">None added yet.</span>}
          </div>
        </div>

        <div className="flex gap-2 pt-2">
          <button
            type="button"
            onClick={onCancel}
            disabled={saving}
            className="flex-1 px-4 py-2 border border-stone-200 rounded-lg text-sm text-stone-600 hover:bg-stone-50 disabled:opacity-50"
          >
            Cancel
          </button>
          <button
            type="submit"
            disabled={saving}
            className="flex-1 flex items-center justify-center gap-1.5 px-4 py-2 bg-(--color-accent) text-white rounded-lg text-sm font-medium hover:bg-(--color-accent-hover) disabled:opacity-50"
          >
            {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
            {saving ? "Saving…" : "Save"}
          </button>
        </div>
        {saveError && (
          <p className="text-sm text-red-500 text-center">{saveError}</p>
        )}
      </form>
    </div>
  );
}