"use client";

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

export default function StripClubRegistrationPage() {
  const router = useRouter();
  const turnstileRef = useRef<TurnstileWidgetHandle>(null);
  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 || []));
  }, [selectedCountry]);

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

    const formData = new FormData(e.currentTarget);
    const data = {
      user_type: "strip_club",
      username: formData.get("username"),
      email: formData.get("email"),
      password: formData.get("password"),
      password_confirmation: formData.get("password_confirmation"),
      country_id: formData.get("country_id"),
      city_id: formData.get("city_id"),
      phone: formData.get("phone") || undefined,
      website: formData.get("website") || undefined,
      address: formData.get("address") || undefined,
      consent_policies: formData.get("consent_policies") === "on",
      consent_gdpr: formData.get("consent_gdpr") === "on",
      consent_emails: formData.get("consent_emails") === "on",
      // Mirror of the consent_policies checkbox so the validator's literal-true
      // confirms_eighteen field passes server-side. Same semantic.
      confirms_eighteen: formData.get("consent_policies") === "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;
      }

      router.push("/verify-email");
    } 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">
        Strip Club Registration
      </h1>
      <p className="text-text-muted text-center mb-6 text-sm">
        List your venue and attract new visitors
      </p>

      {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">
            Club 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 club 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="club@email.com"
          />
          {fieldErrors.email && <p className="text-red-400 text-xs mt-1">{fieldErrors.email}</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="address" className="block text-sm font-medium text-text-muted mb-1">
            Address <span className="text-text-muted">(optional)</span>
          </label>
          <input
            id="address"
            name="address"
            type="text"
            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="123 Main Street"
          />
          {fieldErrors.address && <p className="text-red-400 text-xs mt-1">{fieldErrors.address}</p>}
        </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="website" className="block text-sm font-medium text-text-muted mb-1">
            Website <span className="text-text-muted">(optional)</span>
          </label>
          <input
            id="website"
            name="website"
            type="url"
            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="https://www.yourclub.com"
          />
          {fieldErrors.website && <p className="text-red-400 text-xs mt-1">{fieldErrors.website}</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>
            </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..." : "Register Strip Club"}
        </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>
  );
}
