"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useToastStore } from "@/lib/stores/toast-store";
import TurnstileWidget, { TurnstileWidgetHandle } from "@/components/shared/turnstile-widget";

export default function EscortRegistrationPage() {
  const router = useRouter();
  const turnstileRef = useRef<TurnstileWidgetHandle>(null);
  const addToast = useToastStore((s) => s.addToast);
  const [error, setError] = useState("");
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(false);
  const [countries, setCountries] = useState<{ id: number; name: string }[]>([]);
  const [cities, setCities] = useState<{ id: number; name: string }[]>([]);
  const [selectedCountry, setSelectedCountry] = useState("");
  const [captchaToken, setCaptchaToken] = useState("");

  useEffect(() => {
    fetch("/api/v1/countries?with_cities=true")
      .then((r) => r.json())
      .then((d) => setCountries(d.data || []))
      .catch(() => setCountries([]));
  }, []);

  useEffect(() => {
    if (!selectedCountry) {
      setCities([]);
      return;
    }
    fetch(`/api/v1/countries/${selectedCountry}/cities`)
      .then((r) => r.json())
      .then((d) => setCities(d.data || []))
      .catch(() => setCities([]));
  }, [selectedCountry]);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError("");
    setFieldErrors({});

    const formData = new FormData(e.currentTarget);
    const bornAtRaw = formData.get("born_at") as string | null;

    // Validate born_at is a real ISO date and the user is at least 18.
    // Some browsers will accept an empty <input type="date"> if the OS
    // doesn't render a native picker, and HTML-level validation can't
    // enforce 18+ without a `max` attribute that risks SSR/CSR drift.
    if (!bornAtRaw || typeof bornAtRaw !== "string") {
      setFieldErrors({ born_at: "Date of birth is required" });
      return;
    }
    const born = new Date(bornAtRaw);
    if (Number.isNaN(born.getTime())) {
      setFieldErrors({ born_at: "Please enter a valid date" });
      return;
    }
    const eighteenYearsAgo = new Date();
    eighteenYearsAgo.setFullYear(eighteenYearsAgo.getFullYear() - 18);
    if (born > eighteenYearsAgo) {
      setFieldErrors({ born_at: "You must be at least 18 years old" });
      return;
    }

    setLoading(true);

    const data = {
      user_type: "escort",
      username: formData.get("username"),
      email: formData.get("email"),
      password: formData.get("password"),
      password_confirmation: formData.get("password_confirmation"),
      gender: formData.get("gender"),
      born_at: bornAtRaw,
      country_id: formData.get("country_id"),
      city_id: formData.get("city_id"),
      phone: formData.get("phone") || undefined,
      consent_policies: formData.get("consent_policies") === "on",
      consent_gdpr: formData.get("consent_gdpr") === "on",
      consent_emails: formData.get("consent_emails") === "on",
    };

    if (!captchaToken) {
      setError("Please complete the CAPTCHA challenge.");
      return;
    }

    try {
      const res = await fetch("/api/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...data, captcha_token: captchaToken }),
      });

      const result = await res.json();

      if (!res.ok) {
        // The token was already spent verifying this request server-side,
        // even though it failed for an unrelated reason (validation, etc).
        // Reset so the retry gets a fresh one instead of reusing a dead token.
        turnstileRef.current?.reset();
        setCaptchaToken("");
        if (result.errors) {
          const errs: Record<string, string> = {};
          for (const [key, val] of Object.entries(result.errors)) {
            errs[key] = Array.isArray(val) ? val[0] : (val as string);
          }
          setFieldErrors(errs);
        } else {
          setError(result.message || "Registration failed");
        }
        return;
      }

      addToast(
        "success",
        "Account created — check your email for the verification link"
      );
      // Brief delay so the user sees the toast before the redirect.
      setTimeout(() => router.push("/verify-email"), 1500);
    } catch {
      setError("An unexpected error occurred");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="bg-surface rounded-lg p-8 shadow-lg">
      <h1 className="text-2xl font-bold text-text mb-2 text-center">
        Escort Registration
      </h1>
      <p className="text-text-muted text-center mb-6 text-sm">
        Create your escort profile and start receiving bookings
      </p>

      <div className="bg-amber-500/10 border border-amber-500/50 text-amber-400 rounded-md p-3 mb-4 text-sm">
        You must be at least 18 years old to register as an escort.
      </div>

      {error && (
        <div className="bg-red-500/10 border border-red-500/50 text-red-400 rounded-md p-3 mb-4 text-sm">
          {error}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label htmlFor="username" className="block text-sm font-medium text-text-muted mb-1">
            Display Name
          </label>
          <input
            id="username"
            name="username"
            type="text"
            required
            className="w-full rounded-md border border-surface-light bg-background px-3 py-2 text-text placeholder-text-muted focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
            placeholder="Your display name"
          />
          {fieldErrors.username && <p className="text-red-400 text-xs mt-1">{fieldErrors.username}</p>}
        </div>

        <div>
          <label htmlFor="email" className="block text-sm font-medium text-text-muted mb-1">
            Email
          </label>
          <input
            id="email"
            name="email"
            type="email"
            required
            className="w-full rounded-md border border-surface-light bg-background px-3 py-2 text-text placeholder-text-muted focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
            placeholder="your@email.com"
          />
          {fieldErrors.email && <p className="text-red-400 text-xs mt-1">{fieldErrors.email}</p>}
        </div>

        <div>
          <label htmlFor="gender" className="block text-sm font-medium text-text-muted mb-1">
            Gender
          </label>
          <select
            id="gender"
            name="gender"
            required
            className="w-full rounded-md border border-surface-light bg-background px-3 py-2 text-text focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
          >
            <option value="">Select gender</option>
            <option value="female">Female</option>
            <option value="male">Male</option>
            <option value="trans">Trans</option>
          </select>
          {fieldErrors.gender && <p className="text-red-400 text-xs mt-1">{fieldErrors.gender}</p>}
        </div>

        <div>
          <label htmlFor="born_at" className="block text-sm font-medium text-text-muted mb-1">
            Date of Birth
          </label>
          <input
            id="born_at"
            name="born_at"
            type="date"
            required
            className="w-full rounded-md border border-surface-light bg-background px-3 py-2 text-text focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
          />
          {fieldErrors.born_at && <p className="text-red-400 text-xs mt-1">{fieldErrors.born_at}</p>}
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <label htmlFor="country_id" className="block text-sm font-medium text-text-muted mb-1">
              Country
            </label>
            <select
              id="country_id"
              name="country_id"
              required
              value={selectedCountry}
              onChange={(e) => setSelectedCountry(e.target.value)}
              className="w-full rounded-md border border-surface-light bg-background px-3 py-2 text-text focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
            >
              <option value="">Select country</option>
              {countries.map((c) => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
            {fieldErrors.country_id && <p className="text-red-400 text-xs mt-1">{fieldErrors.country_id}</p>}
          </div>

          <div>
            <label htmlFor="city_id" className="block text-sm font-medium text-text-muted mb-1">
              City
            </label>
            <select
              id="city_id"
              name="city_id"
              required
              className="w-full rounded-md border border-surface-light bg-background px-3 py-2 text-text focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
            >
              <option value="">Select city</option>
              {cities.map((c) => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
            {fieldErrors.city_id && <p className="text-red-400 text-xs mt-1">{fieldErrors.city_id}</p>}
          </div>
        </div>

        <div>
          <label htmlFor="phone" className="block text-sm font-medium text-text-muted mb-1">
            Phone <span className="text-text-muted">(optional)</span>
          </label>
          <input
            id="phone"
            name="phone"
            type="tel"
            className="w-full rounded-md border border-surface-light bg-background px-3 py-2 text-text placeholder-text-muted focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
            placeholder="+44 7700 900000"
          />
          {fieldErrors.phone && <p className="text-red-400 text-xs mt-1">{fieldErrors.phone}</p>}
        </div>

        <div>
          <label htmlFor="password" className="block text-sm font-medium text-text-muted mb-1">
            Password
          </label>
          <input
            id="password"
            name="password"
            type="password"
            required
            className="w-full rounded-md border border-surface-light bg-background px-3 py-2 text-text placeholder-text-muted focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
            placeholder="Min 8 characters"
          />
          {fieldErrors.password && <p className="text-red-400 text-xs mt-1">{fieldErrors.password}</p>}
        </div>

        <div>
          <label htmlFor="password_confirmation" className="block text-sm font-medium text-text-muted mb-1">
            Confirm Password
          </label>
          <input
            id="password_confirmation"
            name="password_confirmation"
            type="password"
            required
            className="w-full rounded-md border border-surface-light bg-background px-3 py-2 text-text placeholder-text-muted focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
            placeholder="Repeat your password"
          />
          {fieldErrors.password_confirmation && <p className="text-red-400 text-xs mt-1">{fieldErrors.password_confirmation}</p>}
        </div>

        <div className="space-y-3 pt-2">
          <label className="flex items-start gap-2 cursor-pointer">
            <input
              name="consent_policies"
              type="checkbox"
              required
              className="mt-1 rounded border-surface-light bg-background text-primary focus:ring-primary"
            />
            <span className="text-sm text-text-muted">
              I agree to the{" "}
              <Link href="/terms-of-service" className="text-primary hover:text-primary-dark">
                Terms of Service
              </Link>{" "}
              and confirm I am at least 18 years old
            </span>
          </label>

          <label className="flex items-start gap-2 cursor-pointer">
            <input
              name="consent_gdpr"
              type="checkbox"
              required
              className="mt-1 rounded border-surface-light bg-background text-primary focus:ring-primary"
            />
            <span className="text-sm text-text-muted">
              I agree to the{" "}
              <Link href="/privacy-policy" className="text-primary hover:text-primary-dark">
                Privacy Policy
              </Link>
            </span>
          </label>

          <label className="flex items-start gap-2 cursor-pointer">
            <input
              name="consent_emails"
              type="checkbox"
              className="mt-1 rounded border-surface-light bg-background text-primary focus:ring-primary"
            />
            <span className="text-sm text-text-muted">
              I would like to receive promotional emails
            </span>
          </label>
        </div>

        <TurnstileWidget ref={turnstileRef} onVerify={setCaptchaToken} />

        <button
          type="submit"
          disabled={loading || !captchaToken}
          className="w-full rounded-md bg-primary py-2.5 text-white font-medium hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 focus:ring-offset-background disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          {loading ? "Creating account..." : "Create Escort Account"}
        </button>
      </form>

      <p className="mt-6 text-center text-sm text-text-muted">
        Already have an account?{" "}
        <Link href="/login" className="text-primary hover:text-primary-dark font-medium">
          Sign In
        </Link>
      </p>
    </div>
  );
}
