"use client";

import { useState } from "react";
import { useRouter } 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 NewInsurancePlanPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({
    name: "", description: "", price: "", yearlyPrice: "",
    badge: "", highlighted: false, active: true,
  });
  const [petTypes, setPetTypes] = useState<string[]>(["dog", "cat"]);
  const [features, setFeatures] = useState<string[]>([""]);
  const [notIncluded, setNotIncluded] = useState<string[]>([""]);

  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", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ...form,
        petTypes,
        features: features.filter(Boolean),
        notIncluded: notIncluded.filter(Boolean),
      }),
    });
    if (res.ok) {
      toast.success("Insurance plan created!");
      router.push("/admin/insurance");
    } else {
      toast.error("Failed to create plan.");
    }
    setLoading(false);
  };

  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">New 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" placeholder="e.g. Complete Care" />
          </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" placeholder="24.99" />
            </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="249.99" />
            </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 ? "Creating…" : "Create Plan"}
          </button>
        </div>
      </form>
    </div>
  );
}
