"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 MemberRegistrationPage() {
  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 [captchaToken, setCaptchaToken] = useState("");
  const [countries, setCountries] = useState<{ id: number; name: string }[]>([]);
  const [detectedCountry, setDetectedCountry] = useState<number | null>(null);
  const [countryId, setCountryId] = useState("");

  // Mirror the async geo-detect into the controlled <select> value once it
  // resolves. Earlier defaultValue= pattern silently lost the auto-detect
  // because React only honors defaultValue on the first render.
  useEffect(() => {
    if (detectedCountry && !countryId) setCountryId(String(detectedCountry));
  }, [detectedCountry, countryId]);

  useEffect(() => {
    // Load countries
    fetch("/api/v1/countries")
      .then((r) => r.json())
      .then((d) => {
        const list = d.data || [];
        setCountries(list);
        // Auto-detect country from browser language/timezone
        try {
          const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
          const lang = navigator.language?.split("-")[1]?.toUpperCase();
          // Simple mapping for common countries
          const tzMap: Record<string, string> = {
            "Europe/London": "United Kingdom", "Europe/Berlin": "Germany",
            "Europe/Paris": "France", "Europe/Madrid": "Spain",
            "Europe/Rome": "Italy", "Europe/Amsterdam": "Netherlands",
            "America/New_York": "United States", "America/Los_Angeles": "United States",
            "Australia/Sydney": "Australia", "Asia/Tokyo": "Japan",
            "Europe/Athens": "Greece", "Europe/Bucharest": "Romania",
          };
          const countryName = tzMap[tz];
          if (countryName) {
            const match = list.find((c: { name: string }) => c.name === countryName);
            if (match) setDetectedCountry(match.id);
          }
        } catch {}
      })
      .catch(() => {});
  }, []);

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

    const formData = new FormData(e.currentTarget);
    const data = {
      user_type: "user",
      username: formData.get("username"),
      email: formData.get("email"),
      password: formData.get("password"),
      password_confirmation: formData.get("password_confirmation"),
      gender: formData.get("gender"),
      born_at: formData.get("born_at"),
      country_id: formData.get("country_id"),
      city_id: formData.get("city_id") || undefined,
      consent_policies: formData.get("consent_policies") === "on",
      consent_gdpr: formData.get("consent_gdpr") === "on",
      consent_emails: formData.get("consent_emails") === "on",
    };

    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">
        Member Registration
      </h1>
      <p className="text-text-muted text-center mb-6 text-sm">
        Create your free member account
      </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">
            Username
          </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="Choose a username"
          />
          {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="male">Male</option>
            <option value="female">Female</option>
            <option value="couple">Couple</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>
          <label htmlFor="country_id" className="block text-sm font-medium text-text-muted mb-1">
            Country <span className="text-text-muted/50 font-normal">(optional)</span>
          </label>
          <select
            id="country_id"
            name="country_id"
            value={countryId}
            onChange={(e) => setCountryId(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 your 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="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}
          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 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>
  );
}
