"use client";

import { useState, useEffect } from "react";
import { Check, X, Shield, ArrowRight } from "lucide-react";
import { InsurancePlan } from "@/types";
import { parseFeatures } from "@/lib/utils";
import toast from "react-hot-toast";

export default function InsurancePage() {
  const [plans, setPlans] = useState<InsurancePlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedPlan, setSelectedPlan] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [billing, setBilling] = useState<"monthly" | "yearly">("monthly");

  const [form, setForm] = useState({
    petName: "",
    petType: "dog",
    petAge: "",
    email: "",
  });

  useEffect(() => {
    fetch("/api/insurance")
      .then((r) => r.json())
      .then((data) => {
        setPlans(data);
        setLoading(false);
      });
  }, []);

  const handleEnroll = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedPlan) return;

    try {
      const res = await fetch("/api/insurance/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ planId: selectedPlan, ...form, billing }),
      });
      const data = await res.json();
      if (data.url) {
        window.location.href = data.url;
      } else {
        toast.error("Failed to start checkout. Please try again.");
      }
    } catch {
      toast.error("Something went wrong.");
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin h-10 w-10 border-4 border-primary-500 border-t-transparent rounded-full" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Hero */}
      <div className="bg-gradient-to-br from-primary-700 to-primary-500 text-white py-20 px-4">
        <div className="max-w-4xl mx-auto text-center">
          <div className="inline-flex items-center gap-2 bg-white/20 px-4 py-2 rounded-full text-sm mb-6">
            <Shield className="h-4 w-4" />
            Pet Health Insurance
          </div>
          <h1 className="text-4xl md:text-5xl font-bold leading-tight">
            Coverage Your Pet Deserves
          </h1>
          <p className="mt-4 text-xl text-primary-100 max-w-2xl mx-auto">
            Comprehensive pet insurance starting at $9.99/month. Reimbursements up to 90%. Any licensed vet in the USA.
          </p>

          <div className="mt-8 inline-flex items-center bg-white/10 rounded-full p-1">
            <button
              onClick={() => setBilling("monthly")}
              className={`px-6 py-2.5 rounded-full text-sm font-semibold transition-all ${billing === "monthly" ? "bg-white text-primary-600" : "text-white"}`}
            >
              Monthly
            </button>
            <button
              onClick={() => setBilling("yearly")}
              className={`px-6 py-2.5 rounded-full text-sm font-semibold transition-all flex items-center gap-2 ${billing === "yearly" ? "bg-white text-primary-600" : "text-white"}`}
            >
              Yearly <span className="bg-accent text-white text-xs px-2 py-0.5 rounded-full">Save 17%</span>
            </button>
          </div>
        </div>
      </div>

      {/* Plans */}
      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 items-stretch">
          {plans.map((plan) => {
            const features = parseFeatures(plan.features);
            const notIncluded = parseFeatures(plan.notIncluded);
            const price = billing === "yearly" ? (plan.yearlyPrice ?? plan.price * 12) / 12 : plan.price;
            const isSelected = selectedPlan === plan.id;

            return (
              <div
                key={plan.id}
                className={`relative rounded-3xl p-8 flex flex-col cursor-pointer transition-all duration-300 ${
                  plan.highlighted
                    ? "bg-primary-600 text-white shadow-2xl shadow-primary-200 scale-105"
                    : isSelected
                    ? "bg-white border-2 border-primary-500 shadow-lg"
                    : "bg-white border-2 border-gray-100 hover:border-primary-200 shadow-sm hover:shadow-lg"
                }`}
                onClick={() => setSelectedPlan(plan.id)}
              >
                {plan.badge && (
                  <div className={`absolute -top-4 left-1/2 -translate-x-1/2 px-4 py-1.5 rounded-full text-sm font-bold ${plan.highlighted ? "bg-accent text-white" : "bg-primary-500 text-white"}`}>
                    {plan.badge}
                  </div>
                )}

                <h3 className={`text-xl font-bold ${plan.highlighted ? "text-white" : "text-gray-900"}`}>{plan.name}</h3>
                <p className={`text-sm mt-2 ${plan.highlighted ? "text-primary-100" : "text-gray-500"}`}>{plan.description}</p>

                <div className="mt-6 mb-8">
                  <span className={`text-4xl font-bold ${plan.highlighted ? "text-white" : "text-gray-900"}`}>
                    ${price.toFixed(2)}
                  </span>
                  <span className={`text-sm ml-1 ${plan.highlighted ? "text-primary-200" : "text-gray-400"}`}>/month</span>
                  {billing === "yearly" && (
                    <div className={`text-xs mt-1 ${plan.highlighted ? "text-primary-200" : "text-gray-400"}`}>
                      Billed ${(plan.yearlyPrice ?? plan.price * 12).toFixed(2)}/year
                    </div>
                  )}
                </div>

                <ul className="space-y-3 flex-1">
                  {features.map((f) => (
                    <li key={f} className="flex items-start gap-2.5 text-sm">
                      <Check className={`h-4 w-4 mt-0.5 shrink-0 ${plan.highlighted ? "text-primary-200" : "text-primary-500"}`} />
                      <span className={plan.highlighted ? "text-white" : "text-gray-700"}>{f}</span>
                    </li>
                  ))}
                  {notIncluded.map((f) => (
                    <li key={f} className="flex items-start gap-2.5 text-sm">
                      <X className={`h-4 w-4 mt-0.5 shrink-0 ${plan.highlighted ? "text-primary-300" : "text-gray-300"}`} />
                      <span className={`line-through ${plan.highlighted ? "text-primary-300" : "text-gray-400"}`}>{f}</span>
                    </li>
                  ))}
                </ul>

                <button
                  onClick={(e) => { e.stopPropagation(); setSelectedPlan(plan.id); setShowForm(true); }}
                  className={`mt-8 w-full py-3.5 px-6 rounded-full font-semibold text-sm transition-all flex items-center justify-center gap-2 ${
                    plan.highlighted
                      ? "bg-white text-primary-600 hover:bg-primary-50"
                      : "bg-primary-500 text-white hover:bg-primary-600"
                  }`}
                >
                  Get Started <ArrowRight className="h-4 w-4" />
                </button>
              </div>
            );
          })}
        </div>

        {/* Enrollment Form */}
        {showForm && selectedPlan && (
          <div className="mt-12 max-w-xl mx-auto bg-white rounded-3xl shadow-lg p-8">
            <h3 className="text-2xl font-bold text-gray-900 mb-2">Enroll Your Pet</h3>
            <p className="text-gray-500 text-sm mb-8">Complete the form below to get started with your plan.</p>
            <form onSubmit={handleEnroll} className="space-y-5">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="label">Pet Name</label>
                  <input
                    type="text"
                    required
                    value={form.petName}
                    onChange={(e) => setForm({ ...form, petName: e.target.value })}
                    className="input-field"
                    placeholder="e.g. Max"
                  />
                </div>
                <div>
                  <label className="label">Pet Age</label>
                  <input
                    type="text"
                    required
                    value={form.petAge}
                    onChange={(e) => setForm({ ...form, petAge: e.target.value })}
                    className="input-field"
                    placeholder="e.g. 3 years"
                  />
                </div>
              </div>
              <div>
                <label className="label">Pet Type</label>
                <select
                  value={form.petType}
                  onChange={(e) => setForm({ ...form, petType: e.target.value })}
                  className="input-field"
                >
                  <option value="dog">Dog</option>
                  <option value="cat">Cat</option>
                  <option value="bird">Bird</option>
                  <option value="rabbit">Rabbit</option>
                  <option value="reptile">Reptile</option>
                  <option value="other">Other</option>
                </select>
              </div>
              <div>
                <label className="label">Your Email</label>
                <input
                  type="email"
                  required
                  value={form.email}
                  onChange={(e) => setForm({ ...form, email: e.target.value })}
                  className="input-field"
                  placeholder="you@example.com"
                />
              </div>
              <button type="submit" className="btn-primary w-full justify-center py-4 text-base">
                <Shield className="h-5 w-5" />
                Proceed to Checkout
              </button>
              <p className="text-xs text-gray-400 text-center">
                Secured by Stripe. Cancel anytime. 30-day money-back guarantee.
              </p>
            </form>
          </div>
        )}
      </div>
    </div>
  );
}
