"use client";

import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { registerUser, loginWithEmail, clearError } from "@/store/slices/authSlice";
import { LoginType } from "@/types/auth";
import { AuthField } from "./AuthField";
import { AuthDivider } from "./AuthDivider";
import { GoogleLoginButton } from "./GoogleLoginButton";
import { useTranslation } from "@/i18n";

const COUNTRY_CODES = [
  { code: "+91", name: "India", iso: "IN" },
  { code: "+1",  name: "USA",   iso: "US" },
  { code: "+44", name: "UK",    iso: "GB" },
  { code: "+61", name: "Australia", iso: "AU" },
  { code: "+971", name: "UAE",  iso: "AE" },
  { code: "+65", name: "Singapore", iso: "SG" },
  { code: "+60", name: "Malaysia",  iso: "MY" },
  { code: "+966", name: "Saudi Arabia", iso: "SA" },
  { code: "+49", name: "Germany", iso: "DE" },
  { code: "+33", name: "France",  iso: "FR" },
];

const schema = z
  .object({
    full_name: z.string().min(2, "Name must be at least 2 characters"),
    email: z.string().email("Enter a valid email"),
    mobile_number: z.string().min(7, "Enter a valid mobile number").max(15, "Mobile number too long").regex(/^\d+$/, "Only digits allowed"),
    password: z.string().min(6, "Password must be at least 6 characters"),
    confirm_password: z.string(),
    terms: z.boolean().refine((v) => v === true, { message: "auth_termsError" }),
  })
  .refine((d) => d.password === d.confirm_password, {
    message: "Passwords do not match",
    path: ["confirm_password"],
  });

type FormValues = z.infer<typeof schema>;

export function SignupForm() {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { isLoading, error } = useAppSelector((s) => s.auth);
  const { t } = useTranslation();

  const [selectedCountry, setSelectedCountry] = useState(COUNTRY_CODES[0]);

  const { register, handleSubmit, formState: { errors } } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: { terms: false },
  });

  const onSubmit = async (data: FormValues) => {
    dispatch(clearError());
    const res = await dispatch(
      registerUser({
        full_name: data.full_name,
        email: data.email,
        password: data.password,
        country_code: selectedCountry.code,
        country_name: selectedCountry.iso,
        mobile_number: data.mobile_number,
      }),
    );
    if (registerUser.fulfilled.match(res)) {
      const loginRes = await dispatch(
        loginWithEmail({ type: LoginType.Normal, email: data.email, password: data.password }),
      );
      if (loginWithEmail.fulfilled.match(loginRes)) {
        router.push("/");
      }
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
      <AuthField
        label={t("auth_fullNameLabel")}
        type="text"
        placeholder="Your full name"
        error={errors.full_name?.message}
        autoComplete="name"
        {...register("full_name")}
      />
      <AuthField
        label={t("auth_emailLabel")}
        type="email"
        placeholder="you@example.com"
        error={errors.email?.message}
        autoComplete="email"
        {...register("email")}
      />

      {/* Mobile number with country code */}
      <div className="flex flex-col gap-1">
        <label className="text-xs font-semibold mb-1" style={{ color: "var(--text-muted)" }}>
          Mobile Number
        </label>
        <div
          className="flex items-stretch rounded-xl overflow-hidden"
          style={{ border: `1px solid ${errors.mobile_number ? "#ef4444" : "var(--border)"}` }}
        >
          <select
            value={selectedCountry.code}
            onChange={(e) => {
              const c = COUNTRY_CODES.find((x) => x.code === e.target.value);
              if (c) setSelectedCountry(c);
            }}
            className="text-xs font-semibold px-2 py-3 focus:outline-none shrink-0"
            style={{
              background: "var(--deep)",
              color: "var(--text-primary)",
              borderRight: "1px solid var(--border)",
              minWidth: 72,
            }}
          >
            {COUNTRY_CODES.map((c) => (
              <option key={c.code} value={c.code} style={{ background: "var(--card)", color: "var(--text-primary)" }}>
                {c.code} {c.iso}
              </option>
            ))}
          </select>
          <input
            type="tel"
            inputMode="numeric"
            placeholder="9876543210"
            autoComplete="tel-national"
            {...register("mobile_number")}
            className="flex-1 px-3 py-3 text-sm focus:outline-none"
            style={{
              background: "var(--deep)",
              color: "var(--text-primary)",
            }}
          />
        </div>
        {errors.mobile_number && (
          <p className="text-xs mt-0.5" style={{ color: "#ef4444" }}>
            {errors.mobile_number.message}
          </p>
        )}
      </div>

      <AuthField
        label={t("auth_passwordLabel")}
        isPassword
        placeholder="••••••••"
        error={errors.password?.message}
        autoComplete="new-password"
        {...register("password")}
      />
      <AuthField
        label={t("auth_confirmPasswordLabel")}
        isPassword
        placeholder="••••••••"
        error={errors.confirm_password?.message}
        autoComplete="new-password"
        {...register("confirm_password")}
      />

      <div className="flex flex-col gap-1">
        <label className="flex items-start gap-2 cursor-pointer select-none">
          <input
            type="checkbox"
            {...register("terms")}
            className="mt-0.5 h-4 w-4 rounded border accent-[var(--accent)] cursor-pointer shrink-0"
          />
          <span className="text-xs leading-relaxed" style={{ color: "var(--text-secondary)" }}>
            {t("auth_termsAgree")}{" "}
            <Link href="/terms" className="underline font-medium hover:opacity-80" style={{ color: "var(--accent)" }}>
              {t("auth_termsLink")}
            </Link>{" "}
            {t("auth_termsAnd")}{" "}
            <Link href="/privacy" className="underline font-medium hover:opacity-80" style={{ color: "var(--accent)" }}>
              {t("auth_privacyLink")}
            </Link>
          </span>
        </label>
        {errors.terms && (
          <p className="text-xs" style={{ color: "#ef4444" }}>
            {t(errors.terms.message as string)}
          </p>
        )}
      </div>

      {error && (
        <p className="text-xs px-3 py-2 rounded-lg" style={{ background: "rgba(239,68,68,0.1)", color: "#ef4444" }}>
          {error}
        </p>
      )}

      <button
        type="submit"
        disabled={isLoading}
        className="w-full py-3 rounded-xl text-sm font-bold tracking-wide text-[#ffffff] transition-all duration-150 active:scale-[0.98] disabled:opacity-60 mt-1"
        style={{ background: "var(--accent)" }}
      >
        {isLoading ? t("auth_creatingAccount") : t("auth_signupButton")}
      </button>

      <AuthDivider />

      <GoogleLoginButton />

      <Link
        href="/auth/otp"
        className="w-full flex items-center justify-center gap-2 rounded-xl py-3 px-4 text-sm font-medium transition-all duration-150 active:scale-[0.98]"
        style={{
          background: "var(--btn-ghost-hover)",
          border: "1px solid var(--border)",
          color: "var(--text-primary)",
        }}
      >
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 12 19.79 19.79 0 0 1 1.63 3.18 2 2 0 0 1 3.6 1h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L7.91 8.1a16 16 0 0 0 6 6l.92-.92a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" />
        </svg>
        {t("auth_phoneOtpButton")}
      </Link>
    </form>
  );
}
