"use client";

import { useMemo, useState } from "react";
import { ArrowRight, CheckCircle2, Loader2 } from "lucide-react";
import type { TicketCountryOption, TicketSearchState } from "./TicketsSlider";

type FormState = "idle" | "submitting" | "success";

export default function TicketRequestForm({
  countries,
  defaults,
}: {
  countries: TicketCountryOption[];
  defaults: TicketSearchState;
}) {
  const [form, setForm] = useState({
    fromCountryId: defaults.fromCountryId,
    fromCityId: defaults.fromCityId,
    toCountryId: defaults.toCountryId,
    toCityId: defaults.toCityId,
    tripType: defaults.tripType,
    departureDate: defaults.departureDate,
    returnDate: defaults.returnDate,
    passengers: defaults.passengers,
    cabinClass: "economy",
    name: "",
    email: "",
    phone: "",
    message: "",
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [formState, setFormState] = useState<FormState>("idle");
  const [submitError, setSubmitError] = useState("");

  const fromCities = useMemo(
    () => countries.find((c) => c.id === form.fromCountryId)?.cities ?? [],
    [countries, form.fromCountryId]
  );
  const toCities = useMemo(
    () => countries.find((c) => c.id === form.toCountryId)?.cities ?? [],
    [countries, form.toCountryId]
  );

  const validate = () => {
    const next: Record<string, string> = {};
    if (!form.fromCountryId) next.fromCountryId = "Select departure country";
    if (!form.fromCityId) next.fromCityId = "Select departure city";
    if (!form.toCountryId) next.toCountryId = "Select destination country";
    if (!form.toCityId) next.toCityId = "Select destination city";
    if (!form.departureDate) next.departureDate = "Departure date is required";
    if (form.tripType === "return_trip" && !form.returnDate) next.returnDate = "Return date is required";
    if (!form.name.trim()) next.name = "Name is required";
    if (!form.email.trim()) next.email = "Email is required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) next.email = "Enter a valid email";
    return next;
  };

  const update = (name: string, value: string | number) => {
    setForm((prev) => ({ ...prev, [name]: value }));
    if (errors[name]) {
      setErrors((prev) => {
        const copy = { ...prev };
        delete copy[name];
        return copy;
      });
    }
  };

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    const nextErrors = validate();
    if (Object.keys(nextErrors).length) {
      setErrors(nextErrors);
      return;
    }

    setFormState("submitting");
    setSubmitError("");

    const res = await fetch("/api/tickets/request", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(form),
    });

    if (!res.ok) {
      const payload = await res.json().catch(() => ({}));
      setSubmitError(payload.error || "Failed to submit request. Please try again.");
      setFormState("idle");
      return;
    }

    setFormState("success");
  };

  if (formState === "success") {
    return (
      <div className="bg-white border border-neutral-200 rounded-2xl p-8 text-center">
        <div className="w-14 h-14 mx-auto rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center mb-4">
          <CheckCircle2 size={28} />
        </div>
        <h3 className="text-xl font-bold text-navy-900">Request Submitted</h3>
        <p className="text-sm text-neutral-500 mt-2">
          Your ticket request has been sent. Our super admin received it in the admin panel and by email.
        </p>
        <button
          className="mt-5 text-sm text-navy-700 hover:text-navy-900 underline"
          onClick={() => {
            setFormState("idle");
            setSubmitError("");
            setForm((prev) => ({
              ...prev,
              name: "",
              email: "",
              phone: "",
              message: "",
            }));
          }}
        >
          Submit another request
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={submit} className="bg-white border border-neutral-200 rounded-2xl p-5 md:p-7 space-y-4">
      <div className="grid md:grid-cols-2 gap-4">
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">From Country *</label>
          <select value={form.fromCountryId} onChange={(e) => update("fromCountryId", e.target.value)} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm">
            <option value="">Select country</option>
            {countries.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
          {errors.fromCountryId && <p className="text-xs text-red-500 mt-1">{errors.fromCountryId}</p>}
        </div>
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">From City *</label>
          <select value={form.fromCityId} onChange={(e) => update("fromCityId", e.target.value)} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm">
            <option value="">Select city</option>
            {fromCities.map((city) => <option key={city.id} value={city.id}>{city.name}</option>)}
          </select>
          {errors.fromCityId && <p className="text-xs text-red-500 mt-1">{errors.fromCityId}</p>}
        </div>
      </div>

      <div className="grid md:grid-cols-2 gap-4">
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">To Country *</label>
          <select value={form.toCountryId} onChange={(e) => update("toCountryId", e.target.value)} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm">
            <option value="">Select country</option>
            {countries.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
          {errors.toCountryId && <p className="text-xs text-red-500 mt-1">{errors.toCountryId}</p>}
        </div>
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">To City *</label>
          <select value={form.toCityId} onChange={(e) => update("toCityId", e.target.value)} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm">
            <option value="">Select city</option>
            {toCities.map((city) => <option key={city.id} value={city.id}>{city.name}</option>)}
          </select>
          {errors.toCityId && <p className="text-xs text-red-500 mt-1">{errors.toCityId}</p>}
        </div>
      </div>

      <div className="grid md:grid-cols-4 gap-4">
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">Trip Type *</label>
          <select
            value={form.tripType}
            onChange={(e) => update("tripType", e.target.value)}
            className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
          >
            <option value="one_way">One Way</option>
            <option value="return_trip">Return</option>
          </select>
        </div>
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">Departure Date *</label>
          <input type="date" value={form.departureDate} onChange={(e) => update("departureDate", e.target.value)} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
          {errors.departureDate && <p className="text-xs text-red-500 mt-1">{errors.departureDate}</p>}
        </div>
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">Return Date</label>
          <input
            type="date"
            value={form.returnDate}
            onChange={(e) => update("returnDate", e.target.value)}
            disabled={form.tripType !== "return_trip"}
            className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm disabled:bg-neutral-100"
          />
          {errors.returnDate && <p className="text-xs text-red-500 mt-1">{errors.returnDate}</p>}
        </div>
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">Passengers *</label>
          <input type="number" min={1} max={9} value={form.passengers} onChange={(e) => update("passengers", Number(e.target.value) || 1)} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
        </div>
      </div>

      <div className="grid md:grid-cols-2 gap-4">
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">Full Name *</label>
          <input type="text" value={form.name} onChange={(e) => update("name", e.target.value)} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" placeholder="Your full name" />
          {errors.name && <p className="text-xs text-red-500 mt-1">{errors.name}</p>}
        </div>
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">Email *</label>
          <input type="email" value={form.email} onChange={(e) => update("email", e.target.value)} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" placeholder="you@email.com" />
          {errors.email && <p className="text-xs text-red-500 mt-1">{errors.email}</p>}
        </div>
      </div>

      <div className="grid md:grid-cols-2 gap-4">
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">Phone Number</label>
          <input type="text" value={form.phone} onChange={(e) => update("phone", e.target.value)} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" placeholder="+60 12-345 6789" />
        </div>
        <div>
          <label className="block text-xs font-semibold text-neutral-600 mb-1">Cabin Class</label>
          <select value={form.cabinClass} onChange={(e) => update("cabinClass", e.target.value)} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm">
            <option value="economy">Economy</option>
            <option value="premium_economy">Premium Economy</option>
            <option value="business">Business</option>
            <option value="first">First Class</option>
          </select>
        </div>
      </div>

      <div>
        <label className="block text-xs font-semibold text-neutral-600 mb-1">Special Notes</label>
        <textarea value={form.message} onChange={(e) => update("message", e.target.value)} rows={3} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" placeholder="Preferred airline, baggage, stopover preferences, etc." />
      </div>

      {submitError && <p className="text-xs text-red-600">{submitError}</p>}

      <button type="submit" disabled={formState === "submitting"} className="w-full md:w-auto inline-flex items-center justify-center gap-2 px-6 py-3 rounded-xl bg-navy-700 hover:bg-navy-800 text-white text-sm font-semibold disabled:opacity-60">
        {formState === "submitting" ? <><Loader2 size={15} className="animate-spin" /> Submitting...</> : <>Submit Ticket Request <ArrowRight size={15} /></>}
      </button>
    </form>
  );
}
