"use client";

import { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import Link from "next/link";
import { ArrowLeft, Save, Plus, X } from "lucide-react";
import toast from "react-hot-toast";

const petTypeOptions = ["dog", "cat", "bird", "rabbit", "reptile", "fish", "small", "all"];

export default function EditInsurancePlanPage() {
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(true);
  const [form, setForm] = useState({
    name: "", description: "", price: "", yearlyPrice: "",
    badge: "", highlighted: false, active: true,
  });
  const [petTypes, setPetTypes] = useState<string[]>([]);
  const [features, setFeatures] = useState<string[]>([""]);
  const [notIncluded, setNotIncluded] = useState<string[]>([""]);

  useEffect(() => {
    fetch(`/api/admin/insurance/${id}`)
      .then((r) => r.json())
      .then((plan: { id: string; name: string; description: string; price: number; yearlyPrice: number | null; petTypes: string; features: string; notIncluded: string; highlighted: boolean; badge: string | null; active: boolean }) => {
        if (!plan || !plan.id) { toast.error("Plan not found"); setFetching(false); return; }
        setForm({
          name: plan.name,
          description: plan.description,
          price: String(plan.price),
          yearlyPrice: plan.yearlyPrice ? String(plan.yearlyPrice) : "",
          badge: plan.badge ?? "",
          highlighted: plan.highlighted,
          active: plan.active,
        });
        try { setPetTypes(JSON.parse(plan.petTypes)); } catch { setPetTypes([]); }
        try { const f = JSON.parse(plan.features); setFeatures(f.length ? f : [""]); } catch { setFeatures([""]); }
        try { const n = JSON.parse(plan.notIncluded); setNotIncluded(n.length ? n : [""]); } catch { setNotIncluded([""]); }
        setFetching(false);
      })
      .catch(() => { toast.error("Failed to load plan."); setFetching(false); });
  }, [id]);

  const addLine = (setter: React.Dispatch<React.SetStateAction<string[]>>) =>
    setter((prev) => [...prev, ""]);
  const updateLine = (setter: React.Dispatch<React.SetStateAction<string[]>>, i: number, val: string) =>
    setter((prev) => prev.map((v, idx) => (idx === i ? val : v)));
  const removeLine = (setter: React.Dispatch<React.SetStateAction<string[]>>, i: number) =>
    setter((prev) => prev.filter((_, idx) => idx !== i));
  const togglePetType = (pt: string) =>
    setPetTypes((prev) => prev.includes(pt) ? prev.filter((t) => t !== pt) : [...prev, pt]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    const res = await fetch(`/api/admin/insurance/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ...form,
        petTypes,
        features: features.filter(Boolean),
        notIncluded: notIncluded.filter(Boolean),
      }),
    });
    if (res.ok) {
      toast.success("Plan updated!");
      router.push("/admin/insurance");
    } else {
      toast.error("Failed to update plan.");
    }
    setLoading(false);
  };

  if (fetching) return <div className="p-8 text-gray-500">Loading plan...</div>;

  return (
    <div className="p-8 max-w-3xl">
      <div className="flex items-center gap-4 mb-8">
        <Link href="/admin/insurance" className="p-2 hover:bg-gray-200 rounded-xl transition-colors">
          <ArrowLeft className="h-5 w-5 text-gray-600" />
        </Link>
        <h1 className="text-2xl font-bold text-gray-900">Edit Insurance Plan</h1>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="bg-white rounded-2xl shadow-sm p-8 space-y-5">
          <h2 className="font-semibold text-gray-700 text-sm uppercase tracking-wider">Basic Info</h2>
          <div>
            <label className="label">Plan Name *</label>
            <input required value={form.name} onChange={e => setForm({...form, name: e.target.value})} className="input-field" />
          </div>
          <div>
            <label className="label">Description *</label>
            <textarea required rows={3} value={form.description} onChange={e => setForm({...form, description: e.target.value})} className="input-field resize-none" />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="label">Monthly Price ($) *</label>
              <input type="number" step="0.01" required value={form.price} onChange={e => setForm({...form, price: e.target.value})} className="input-field" />
            </div>
            <div>
              <label className="label">Yearly Price ($)</label>
              <input type="number" step="0.01" value={form.yearlyPrice} onChange={e => setForm({...form, yearlyPrice: e.target.value})} className="input-field" placeholder="Optional" />
            </div>
          </div>
          <div>
            <label className="label">Badge Label</label>
            <input value={form.badge} onChange={e => setForm({...form, badge: e.target.value})} className="input-field" placeholder='e.g. "Most Popular"' />
          </div>
          <div className="flex gap-6">
            <label className="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" checked={form.highlighted} onChange={e => setForm({...form, highlighted: e.target.checked})} className="w-4 h-4 accent-primary-500" />
              <span className="text-sm font-medium text-gray-700">Highlighted (featured)</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" checked={form.active} onChange={e => setForm({...form, active: e.target.checked})} className="w-4 h-4 accent-primary-500" />
              <span className="text-sm font-medium text-gray-700">Active</span>
            </label>
          </div>
        </div>

        <div className="bg-white rounded-2xl shadow-sm p-8 space-y-4">
          <h2 className="font-semibold text-gray-700 text-sm uppercase tracking-wider">Eligible Pet Types</h2>
          <div className="flex flex-wrap gap-2">
            {petTypeOptions.map((pt) => (
              <button
                key={pt}
                type="button"
                onClick={() => togglePetType(pt)}
                className={`px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors capitalize ${
                  petTypes.includes(pt)
                    ? "bg-primary-500 text-white border-primary-500"
                    : "bg-white text-gray-600 border-gray-200 hover:border-primary-300"
                }`}
              >
                {pt}
              </button>
            ))}
          </div>
        </div>

        <div className="bg-white rounded-2xl shadow-sm p-8 space-y-4">
          <h2 className="font-semibold text-gray-700 text-sm uppercase tracking-wider">What&apos;s Included</h2>
          {features.map((feat, i) => (
            <div key={i} className="flex gap-2">
              <input value={feat} onChange={e => updateLine(setFeatures, i, e.target.value)} className="input-field flex-1" placeholder="e.g. Emergency vet visits" />
              {features.length > 1 && (
                <button type="button" onClick={() => removeLine(setFeatures, i)} className="p-2 hover:bg-red-50 text-red-400 rounded-lg">
                  <X className="h-4 w-4" />
                </button>
              )}
            </div>
          ))}
          <button type="button" onClick={() => addLine(setFeatures)} className="flex items-center gap-1.5 text-sm text-primary-600 hover:text-primary-700 font-medium">
            <Plus className="h-4 w-4" /> Add feature
          </button>
        </div>

        <div className="bg-white rounded-2xl shadow-sm p-8 space-y-4">
          <h2 className="font-semibold text-gray-700 text-sm uppercase tracking-wider">Not Included</h2>
          {notIncluded.map((item, i) => (
            <div key={i} className="flex gap-2">
              <input value={item} onChange={e => updateLine(setNotIncluded, i, e.target.value)} className="input-field flex-1" placeholder="e.g. Pre-existing conditions" />
              {notIncluded.length > 1 && (
                <button type="button" onClick={() => removeLine(setNotIncluded, i)} className="p-2 hover:bg-red-50 text-red-400 rounded-lg">
                  <X className="h-4 w-4" />
                </button>
              )}
            </div>
          ))}
          <button type="button" onClick={() => addLine(setNotIncluded)} className="flex items-center gap-1.5 text-sm text-primary-600 hover:text-primary-700 font-medium">
            <Plus className="h-4 w-4" /> Add exclusion
          </button>
        </div>

        <div className="flex gap-3">
          <Link href="/admin/insurance" className="btn-outline">Cancel</Link>
          <button type="submit" disabled={loading} className="btn-primary disabled:opacity-70">
            <Save className="h-4 w-4" />
            {loading ? "Saving…" : "Update Plan"}
          </button>
        </div>
      </form>
    </div>
  );
}
