"use client";

import { useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  RecaptchaVerifier,
  signInWithPhoneNumber,
  ConfirmationResult,
} from "firebase/auth";
import { auth } from "@/lib/firebase";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { loginWithOTP, clearError } from "@/store/slices/authSlice";
import { LoginType } from "@/types/auth";
import { OtpInput } from "./OtpInput";
import { ResendTimer } from "./ResendTimer";
import { useTranslation } from "@/i18n";
import { ArrowLeft } from "lucide-react";
import Link from "next/link";

const phoneSchema = z.object({
  country_code: z.string().min(1, "Select country code"),
  mobile_number: z.string().min(7, "Enter a valid phone number").max(15),
});
type PhoneValues = z.infer<typeof phoneSchema>;

const COUNTRY_CODES = [
  { code: "+91", name: "India" },
  { code: "+1", name: "USA" },
  { code: "+44", name: "UK" },
  { code: "+971", name: "UAE" },
  { code: "+61", name: "Australia" },
  { code: "+81", name: "Japan" },
];

export function OtpPage() {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { isLoading } = useAppSelector((s) => s.auth);

  const { t } = useTranslation();
  const [step, setStep] = useState<"phone" | "otp">("phone");
  const [otpValue, setOtpValue] = useState("123456");
  const [otpError, setOtpError] = useState("");
  const [sendingOtp, setSendingOtp] = useState(false);
  const [verifying, setVerifying] = useState(false);
  const [phoneInfo, setPhoneInfo] = useState({
    code: "+91",
    number: "9898989898",
    country: "India",
  });
  const confirmationRef = useRef<ConfirmationResult | null>(null);

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<PhoneValues>({
    resolver: zodResolver(phoneSchema),
    defaultValues: { country_code: "+91", mobile_number: "9898989898" },
  });

  const selectedCode = watch("country_code");

  const sendOtp = async (data: PhoneValues) => {
    setSendingOtp(true);
    setOtpError("");
    try {
      const recaptchaVerifier = new RecaptchaVerifier(
        auth,
        "recaptcha-container",
        {
          size: "invisible",
          callback: () => {},
        },
      );
      const fullPhone = `${data.country_code}${data.mobile_number}`;
      const result = await signInWithPhoneNumber(
        auth,
        fullPhone,
        recaptchaVerifier,
      );
      confirmationRef.current = result;
      const country = COUNTRY_CODES.find((c) => c.code === data.country_code);
      setPhoneInfo({
        code: data.country_code,
        number: data.mobile_number,
        country: country?.name ?? "India",
      });
      setStep("otp");
    } catch (err: unknown) {
      setOtpError(err instanceof Error ? err.message : t("auth_failedSendOtp"));
    } finally {
      setSendingOtp(false);
    }
  };

  const verifyOtp = async () => {
    if (otpValue.length < 6) {
      setOtpError(t("auth_enterOtp"));
      return;
    }
    if (!confirmationRef.current) return;
    setVerifying(true);
    setOtpError("");
    try {
      const credential = await confirmationRef.current.confirm(otpValue);
      const firebaseUid = credential.user.uid;
      const res = await dispatch(
        loginWithOTP({
          type: LoginType.OTP,
          firebase_id: firebaseUid,
          mobile_number: phoneInfo.number,
          country_code: phoneInfo.code.replace("+", ""),
          country_name: phoneInfo.country,
        }),
      );
      if (loginWithOTP.fulfilled.match(res)) {
        router.push("/");
      } else {
        setOtpError(t("auth_verificationFailed"));
      }
    } catch {
      setOtpError(t("auth_invalidOtp"));
    } finally {
      setVerifying(false);
    }
  };

  const handleResend = async () => {
    setSendingOtp(true);
    try {
      const recaptchaVerifier = new RecaptchaVerifier(
        auth,
        "recaptcha-container",
        {
          size: "invisible",
          callback: () => {},
        },
      );
      const fullPhone = `${phoneInfo.code}${phoneInfo.number}`;
      const result = await signInWithPhoneNumber(
        auth,
        fullPhone,
        recaptchaVerifier,
      );
      confirmationRef.current = result;
      setOtpValue("");
      setOtpError("");
    } catch {
      setOtpError(t("auth_failedResendOtp"));
    } finally {
      setSendingOtp(false);
    }
  };

  return (
    <div
      className="rounded-2xl p-8"
      style={{
        background: "var(--auth-card-bg)",
        backdropFilter: "blur(20px)",
        WebkitBackdropFilter: "blur(20px)",
        border: "1px solid var(--border)",
        boxShadow: "var(--auth-card-shadow)",
      }}
    >
      {/* Back */}
      <Link
        href="/auth/login"
        className="inline-flex items-center gap-2 text-xs font-medium mb-6 transition-opacity hover:opacity-80"
        style={{ color: "var(--text-muted)" }}
      >
        <ArrowLeft size={14} /> {t("auth_backToLogin")}
      </Link>

      {step === "phone" ? (
        <>
          <h1
            className="text-2xl font-black tracking-tight mb-1"
            style={{ color: "var(--text-primary)" }}
          >
            {t("auth_otpTitle")}
          </h1>
          <p className="text-sm mb-7" style={{ color: "var(--text-muted)" }}>
            {t("auth_otpSubtext")}
          </p>

          <form
            onSubmit={handleSubmit(sendOtp)}
            className="flex flex-col gap-4"
          >
            <div className="flex flex-col gap-1.5">
              <label
                className="text-xs font-semibold tracking-wide uppercase"
                style={{ color: "var(--text-muted)" }}
              >
                {t("auth_countryCode")}
              </label>
              <select
                {...register("country_code")}
                className="w-full rounded-xl px-4 py-3 text-sm outline-none"
                style={{
                  background: "var(--deep)",
                  border: "1.5px solid var(--border)",
                  color: "var(--text-primary)",
                }}
              >
                {COUNTRY_CODES.map((c) => (
                  <option
                    key={c.code}
                    value={c.code}
                    style={{ background: "var(--card)" }}
                  >
                    {c.code} — {c.name}
                  </option>
                ))}
              </select>
              {errors.country_code && (
                <p className="text-xs" style={{ color: "#ef4444" }}>
                  {errors.country_code.message}
                </p>
              )}
            </div>

            <div className="flex flex-col gap-1.5">
              <label
                className="text-xs font-semibold tracking-wide uppercase"
                style={{ color: "var(--text-muted)" }}
              >
                {t("auth_phoneNumber")}
              </label>
              <div className="flex gap-2">
                <div
                  className="flex items-center px-3 rounded-xl text-sm font-medium"
                  style={{
                    background: "var(--deep)",
                    border: "1.5px solid var(--border)",
                    color: "var(--accent)",
                    minWidth: "64px",
                  }}
                >
                  {selectedCode}
                </div>
                <input
                  {...register("mobile_number")}
                  type="tel"
                  placeholder="9876543210"
                  className="flex-1 rounded-xl px-4 py-3 text-sm outline-none"
                  style={{
                    background: "var(--deep)",
                    border: `1.5px solid ${errors.mobile_number ? "#ef4444" : "var(--border)"}`,
                    color: "var(--text-primary)",
                  }}
                  onFocus={(e) => {
                    e.currentTarget.style.borderColor = "var(--accent)";
                  }}
                  onBlur={(e) => {
                    e.currentTarget.style.borderColor = "var(--border)";
                  }}
                />
              </div>
              {errors.mobile_number && (
                <p className="text-xs" style={{ color: "#ef4444" }}>
                  {errors.mobile_number.message}
                </p>
              )}
            </div>

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

            <button
              type="submit"
              disabled={sendingOtp}
              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)" }}
            >
              {sendingOtp ? t("auth_sending") : t("auth_sendOtp")}
            </button>
          </form>
        </>
      ) : (
        <>
          <h1
            className="text-2xl font-black tracking-tight mb-1"
            style={{ color: "var(--text-primary)" }}
          >
            {t("auth_verifyOtpTitle")}
          </h1>
          <p className="text-sm mb-7" style={{ color: "var(--text-muted)" }}>
            {t("auth_codeSentTo")}{" "}
            <span style={{ color: "var(--accent)" }}>
              {phoneInfo.code} {phoneInfo.number}
            </span>
          </p>

          <div className="flex flex-col gap-6">
            <OtpInput
              value={otpValue}
              onChange={setOtpValue}
              error={otpError}
            />

            <button
              onClick={verifyOtp}
              disabled={verifying || 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"
              style={{ background: "var(--accent)" }}
            >
              {verifying ? t("auth_verifying") : t("auth_verifyOtp")}
            </button>

            <ResendTimer onResend={handleResend} />
          </div>
        </>
      )}

      {/* Hidden recaptcha container — required for Firebase invisible reCAPTCHA */}
      <div id="recaptcha-container" />
    </div>
  );
}
