"use client";

import Link from "next/link";
import Script from "next/script";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Apple, Mail } from "lucide-react";
import { MainHeader } from "@/components/layout/main-header";
import { MainFooter } from "@/components/shared/main-footer";
import { AuthShell } from "@/components/shared/auth-shell";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useAuth } from "@/providers/auth-provider";
import { useLocale } from "@/providers/locale-provider";
import { useToast } from "@/providers/toast-provider";
import { getApiErrorMessage } from "@/lib/api/client";
import { usePublicSettingsQuery } from "@/hooks/queries/api-hooks";

const loginSchema = z.object({
  login: z.string().min(3, "أدخل البريد الإلكتروني أو رقم الهاتف"),
  password: z.string().min(6, "كلمة المرور قصيرة"),
});

type LoginForm = z.infer<typeof loginSchema>;

function setting(settings: Array<{ key: string; value: string | null }>, key: string): string {
  return settings.find((item) => item.key === key)?.value?.trim() || "";
}

export default function LoginPage() {
  const router = useRouter();
  const { login, socialLogin } = useAuth();
  const { locale } = useLocale();
  const isArabic = locale === "ar";
  const { showToast } = useToast();
  const [emailMode, setEmailMode] = useState(false);
  const [socialLoading, setSocialLoading] = useState<"" | "google" | "apple">("");

  const publicSettingsQuery = usePublicSettingsQuery(["social_google_client_id", "social_apple_client_id"]);
  const publicSettings = publicSettingsQuery.data || [];
  const googleClientId = setting(publicSettings, "social_google_client_id");
  const appleClientId = setting(publicSettings, "social_apple_client_id");

  const callbackUrl = useMemo(() => {
    if (typeof window === "undefined") {
      return "";
    }
    return `${window.location.origin}/login`;
  }, []);

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<LoginForm>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      login: "",
      password: "",
    },
  });

  const onSubmit = async (values: LoginForm) => {
    try {
      await login(values);
      showToast({ type: "success", title: isArabic ? "تم تسجيل الدخول بنجاح" : "Logged in successfully" });
      router.push("/account");
    } catch (error) {
      showToast({
        type: "error",
        title: isArabic ? "فشل تسجيل الدخول" : "Login failed",
        description: getApiErrorMessage(error),
      });
    }
  };

  const handleGoogleLogin = async () => {
    const googleId = window.google?.accounts?.id;

    if (!googleId || !googleClientId) {
      showToast({
        type: "error",
        title: isArabic ? "Google غير مفعّل" : "Google is not configured",
        description: isArabic ? "أضف social_google_client_id من لوحة الأدمن." : "Set social_google_client_id from admin settings.",
      });
      return;
    }

    setSocialLoading("google");

    try {
      const idToken = await new Promise<string>((resolve, reject) => {
        googleId.initialize({
          client_id: googleClientId,
          callback: (response: { credential?: string }) => {
            if (response.credential) {
              resolve(response.credential);
            } else {
              reject(new Error("Google token was not returned"));
            }
          },
          auto_select: false,
          cancel_on_tap_outside: true,
        });

        googleId.prompt((notification: { isNotDisplayed?: () => boolean; isSkippedMoment?: () => boolean }) => {
          if (notification?.isNotDisplayed?.() || notification?.isSkippedMoment?.()) {
            reject(new Error("Google prompt was dismissed"));
          }
        });
      });

      await socialLogin({ provider: "google", id_token: idToken, device_name: "web-google" });
      showToast({ type: "success", title: isArabic ? "تم تسجيل الدخول عبر Google" : "Logged in with Google" });
      router.push("/account");
    } catch (error) {
      showToast({
        type: "error",
        title: isArabic ? "فشل تسجيل الدخول عبر Google" : "Google login failed",
        description: getApiErrorMessage(error),
      });
    } finally {
      setSocialLoading("");
    }
  };

  const handleAppleLogin = async () => {
    const appleAuth = window.AppleID?.auth;

    if (!appleAuth || !appleClientId) {
      showToast({
        type: "error",
        title: isArabic ? "Apple غير مفعّل" : "Apple is not configured",
        description: isArabic ? "أضف social_apple_client_id من لوحة الأدمن." : "Set social_apple_client_id from admin settings.",
      });
      return;
    }

    setSocialLoading("apple");

    try {
      appleAuth.init({
        clientId: appleClientId,
        scope: "name email",
        redirectURI: callbackUrl || window.location.href,
        usePopup: true,
      });

      const response = await appleAuth.signIn();
      const idToken = response?.authorization?.id_token;

      if (!idToken) {
        throw new Error("Apple token was not returned");
      }

      await socialLogin({ provider: "apple", id_token: idToken, device_name: "web-apple" });
      showToast({ type: "success", title: isArabic ? "تم تسجيل الدخول عبر Apple" : "Logged in with Apple" });
      router.push("/account");
    } catch (error) {
      showToast({
        type: "error",
        title: isArabic ? "فشل تسجيل الدخول عبر Apple" : "Apple login failed",
        description: getApiErrorMessage(error),
      });
    } finally {
      setSocialLoading("");
    }
  };

  return (
    <div>
      <Script src="https://accounts.google.com/gsi/client" strategy="afterInteractive" />
      <Script src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/ar_AR/appleid.auth.js" strategy="afterInteractive" />

      <MainHeader />
      <main className="container-shell section-space">
        <AuthShell
          title={isArabic ? "تسجيل الدخول" : "Login"}
          subtitle={isArabic ? "اختر طريقة الدخول المفضلة لديك." : "Choose your preferred sign-in method."}
        >
          <div className="space-y-3">
            <Button className="w-full" variant="secondary" onClick={() => setEmailMode((prev) => !prev)}>
              <Mail size={16} />
              {isArabic ? "المتابعة عبر البريد الإلكتروني" : "Continue with Email"}
            </Button>

            <Button className="w-full" onClick={() => void handleGoogleLogin()} disabled={socialLoading === "google"}>
              {socialLoading === "google" ? (isArabic ? "جارٍ المعالجة..." : "Processing...") : "Continue with Google"}
            </Button>

            <Button className="w-full" variant="secondary" onClick={() => void handleAppleLogin()} disabled={socialLoading === "apple"}>
              <Apple size={16} />
              {socialLoading === "apple" ? (isArabic ? "جارٍ المعالجة..." : "Processing...") : "Continue with Apple"}
            </Button>
          </div>

          {emailMode ? (
            <form className="mt-6 space-y-4 border-t border-[var(--border)] pt-5" onSubmit={(event) => void handleSubmit(onSubmit)(event)}>
              <div>
                <label className="mb-1 block text-xs font-bold text-slate-600">{isArabic ? "البريد الإلكتروني أو الهاتف" : "Email or phone"}</label>
                <Input placeholder={isArabic ? "example@mail.com أو 010..." : "example@mail.com or +20..."} {...register("login")} />
                {errors.login ? <p className="mt-1 text-xs text-rose-600">{errors.login.message}</p> : null}
              </div>

              <div>
                <label className="mb-1 block text-xs font-bold text-slate-600">{isArabic ? "كلمة المرور" : "Password"}</label>
                <Input type="password" placeholder="********" {...register("password")} />
                {errors.password ? <p className="mt-1 text-xs text-rose-600">{errors.password.message}</p> : null}
              </div>

              <Button className="w-full" type="submit" disabled={isSubmitting}>
                {isSubmitting ? (isArabic ? "جارٍ التحقق..." : "Checking...") : (isArabic ? "دخول" : "Login")}
              </Button>
            </form>
          ) : null}

          <div className="mt-4 flex items-center justify-between text-xs text-slate-500">
            <Link className="font-semibold text-teal-700" href="/forgot-password">
              {isArabic ? "نسيت كلمة المرور؟" : "Forgot password?"}
            </Link>
            <span>
              {isArabic ? "ليس لديك حساب؟" : "No account?"}{" "}
              <Link className="font-semibold text-teal-700" href="/register">
                {isArabic ? "سجل الآن" : "Create one"}
              </Link>
            </span>
          </div>
        </AuthShell>
      </main>
      <MainFooter />
    </div>
  );
}
