"use client";

import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "@/store/store";
import { login, clearError } from "@/store/slices/auth-slice";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { PasswordInput } from "@/components/ui/password-input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import toast from "react-hot-toast";
import { useTranslations, useLocale } from "next-intl";
import { useRouter } from "next/navigation";
import { Badge } from "../ui/badge";
import { BeatLoader } from "react-spinners";
import { Loader2 } from "lucide-react";

interface LoginFormProps {
  onSwitchToRegister: () => void;
  onForgotPassword: () => void;
  onLoginSuccess?: () => void; // optional callback to override default redirect
}

type LoginMode = "phone" | "email";

export default function LoginForm({
  onSwitchToRegister,
  onForgotPassword,
  onLoginSuccess,
}: LoginFormProps) {
  const t = useTranslations("auth");
  const locale = useLocale();
  const router = useRouter();
  const dispatch = useDispatch<AppDispatch>();

  // Same flag-driven approach as LoginPageBalmy: settings.LoginByMobile
  // true  => phone-only login, false => email-only login.
  // null  => still loading the flag.
  const [loginByMobile, setLoginByMobile] = useState<boolean | null>(null);
  const loginMode: LoginMode = loginByMobile ? "phone" : "email";

  const [email, setEmail] = useState("");
  const [phoneNumber, setPhoneNumber] = useState("");
  const [password, setPassword] = useState("");
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [isLoading, setIsLoading] = useState(false);

  // Clear any stale Redux auth errors on mount
  useEffect(() => {
    dispatch(clearError());
  }, [dispatch]);

  // Match LoginPageBalmy: fetch LoginByMobile from settings to choose login method.
  useEffect(() => {
    let cancelled = false;

    async function loadLoginMethod() {
      try {
        const res = await fetch(
          `/api/catalog/settings?locale=${encodeURIComponent(locale)}`,
          {
            method: "GET",
            headers: { "Content-Type": "application/json" },
          }
        );
        const data = await res.json().catch(() => null);
        if (cancelled) return;

        const flag = data?.LoginByMobile;
        const enabled =
          flag === true || flag === 1 || flag === "1" || flag === "true";
        setLoginByMobile(enabled);
      } catch {
        if (cancelled) return;
        // If settings fails, default to email (safer).
        setLoginByMobile(false);
      }
    }

    loadLoginMethod();
    return () => {
      cancelled = true;
    };
  }, [locale]);

  const clearFieldError = (fieldName: string) => {
    if (fieldErrors[fieldName]) {
      setFieldErrors((prev) => ({ ...prev, [fieldName]: "" }));
    }
  };

  const validate = (): boolean => {
    const errors: Record<string, string> = {};

    if (loginMode === "phone") {
      if (!phoneNumber || phoneNumber.length < 9) {
        errors.phone = t("please-enter-valid-phone");
      }
    } else {
      if (!email.trim()) {
        errors.email = t("email-required");
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        errors.email = t("invalid-email");
      }
    }

    if (!password) {
      errors.password = t("password-required");
    }

    setFieldErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    setIsLoading(true);
    dispatch(clearError());

    // Markatty backend uses `username`, so phone-as-username works the same
    // as email-as-username — matching LoginPageBalmy.
    const username = loginMode === "phone" ? phoneNumber : email;

    try {
      const result = await dispatch(login({ email: username, password }));
      if (login.fulfilled.match(result)) {
        toast.success(t("login-successful"));
        if (onLoginSuccess) {
          onLoginSuccess();
        } else {
          router.push(`/${locale}/home`);
        }
      } else {
        toast.error((result.payload as string) || t("login-failed"));
      }
    } catch (error) {
      toast.error(t("unexpected-error"));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader className="text-center">
        <CardTitle className="text-2xl font-bold">{t("login")}</CardTitle>
        <p className="text-muted-foreground">{t("welcome-back")}</p>
      </CardHeader>
      <CardContent>
        {loginByMobile === null ? (
          <div className="flex items-center justify-center py-6">
            <Loader2 className="w-5 h-5 animate-spin text-gray-400" />
          </div>
        ) : (
          <form onSubmit={onSubmit} className="space-y-4">
            {loginMode === "phone" ? (
              <div className="space-y-1">
                <Label className="block text-sm font-medium text-start">
                  {t("phone-label") || t("phone") || "رقم الهاتف"}
                </Label>
                <div
                  className={`flex border rounded-md overflow-hidden transition-all duration-200 ${
                    fieldErrors.phone
                      ? "border-red-500"
                      : "border-input focus-within:ring-2 focus-within:ring-ring"
                  }`}
                  dir="ltr"
                >
                  <div className="flex items-center px-3 bg-gray-50 border-r border-input text-gray-600 text-sm">
                    +966
                  </div>
                  <input
                    type="tel"
                    value={phoneNumber}
                    onChange={(e) => {
                      setPhoneNumber(e.target.value.replace(/\D/g, ""));
                      clearFieldError("phone");
                    }}
                    placeholder={t("phone-placeholder") || ""}
                    className="flex-1 px-3 py-2 focus:outline-none text-sm bg-transparent"
                    maxLength={10}
                    dir="ltr"
                  />
                </div>
                {fieldErrors.phone && (
                  <p className="text-red-500 text-sm mt-1 text-start">
                    {fieldErrors.phone}
                  </p>
                )}
              </div>
            ) : (
              <div className="space-y-1">
                <Label className="block text-sm font-medium text-start">
                  {t("email") || "البريد الإلكتروني"}
                </Label>
                <Input
                  type="email"
                  dir="ltr"
                  value={email}
                  onChange={(e) => {
                    setEmail(e.target.value);
                    clearFieldError("email");
                  }}
                  placeholder={t("email-placeholder")}
                  className={fieldErrors.email ? "border-red-500" : ""}
                />
                {fieldErrors.email && (
                  <p className="text-red-500 text-sm mt-1 text-start">
                    {fieldErrors.email}
                  </p>
                )}
              </div>
            )}

            <div className="space-y-1">
              <Label className="block text-sm font-medium text-start">
                {t("password") || "كلمة المرور"}
              </Label>
              <PasswordInput
                value={password}
                onChange={(e) => {
                  setPassword(e.target.value);
                  clearFieldError("password");
                }}
                placeholder={t("password-placeholder")}
                className={fieldErrors.password ? "border-red-500" : ""}
              />
              {fieldErrors.password && (
                <p className="text-red-500 text-sm mt-1 text-start">
                  {fieldErrors.password}
                </p>
              )}
            </div>

            <Button type="submit" className="w-full" disabled={isLoading}>
              {isLoading ? (
                <p className="flex items-center gap-2">
                  <Badge className="text-base bg-transparent text-white">
                    {t("sign-in")}
                  </Badge>{" "}
                  <BeatLoader color="#fff" size={3} />
                </p>
              ) : (
                t("sign-in")
              )}
            </Button>

            <div className="text-center flex gap-5 justify-between items-center">
              <div>
                <button
                  type="button"
                  onClick={onSwitchToRegister}
                  className="text-primary underline text-sm hover:text-primary/80"
                >
                  {t("dont-have-account")}
                </button>
              </div>
              <div>
                <button
                  type="button"
                  className="text-primary underline text-sm hover:text-primary/80"
                  onClick={onForgotPassword}
                >
                  {t("forgot-password")}
                </button>
              </div>
            </div>
          </form>
        )}
      </CardContent>
    </Card>
  );
}
