"use client";

import { Suspense, useState, useEffect } from "react";
import dynamic from "next/dynamic";
import { SignIn, useAuth } from "@clerk/nextjs";
import Link from "next/link";
import { useParams, useSearchParams, useRouter } from "next/navigation";
import { UI, type Lang } from "@/lib/config";
import BrandLogo from "@/components/BrandLogo";
import AuthBackButton from "@/components/auth/AuthBackButton";
import ClerkWidgetSkeleton from "@/components/auth/ClerkWidgetSkeleton";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _ClerkSignIn = dynamic(
  () => import("@clerk/nextjs").then((mod) => mod.SignIn),
  {
    ssr: false,
    loading: () => <ClerkWidgetSkeleton />,
  },
);

function resolveRedirectTarget(value: string | null, fallback: string): string {
  if (!value?.startsWith("/")) return fallback;
  if (value.startsWith("//")) return fallback;
  return value;
}

export default function ClerkLoginPage() {
  return (
    <Suspense>
      <ClerkLoginContent />
    </Suspense>
  );
}

function ClerkLoginContent() {
  const params = useParams();
  const searchParams = useSearchParams();
  const router = useRouter();
  const { isSignedIn, isLoaded } = useAuth();
  const [mounted, setMounted] = useState(false);
  const lang = (params?.lang as Lang) || "en";
  const dir = UI[lang].dir;
  const isAr = lang === "ar";
  const redirectTarget = resolveRedirectTarget(
    searchParams.get("redirect_url"),
    `/${lang}/dashboard`,
  );

  // Only render Clerk component on client (prevents hydration mismatch)
  useEffect(() => {
    setMounted(true);
  }, []);

  // Fallback redirect: if user is already signed in, navigate to dashboard
  // BUT: detect redirect loop — if we came from dashboard, don't auto-redirect
  // back (that causes an infinite loop when server-side auth fails but client-side succeeds)
  useEffect(() => {
    if (isLoaded && isSignedIn) {
      const fromDashboard = searchParams
        .get("redirect_url")
        ?.includes("/dashboard");
      const loopKey = "clerk_redirect_count";
      const count = parseInt(sessionStorage.getItem(loopKey) || "0");

      if (fromDashboard && count >= 1) {
        // We've been here before from dashboard — break the loop
        // Clear the counter and show the sign-in form (forces re-auth)
        sessionStorage.removeItem(loopKey);
        // Don't redirect — let user interact with the page
        return;
      }

      // Track redirect attempts
      sessionStorage.setItem(loopKey, String(count + 1));
      // Clear counter after 10 seconds (normal navigation resets it)
      setTimeout(() => sessionStorage.removeItem(loopKey), 10000);

      router.replace(redirectTarget);
    }
  }, [isLoaded, isSignedIn, redirectTarget, router, searchParams]);

  const features = isAr
    ? [
        { icon: "🤖", text: "وكلاء صوتيون ودردشة ذكية بالعربية والإنجليزية" },
        { icon: "📅", text: "حجوزات آلية في أقل من ١٠ ثوانٍ" },
        { icon: "📊", text: "تقليل عدم الحضور بنسبة ٨٥٪ وأكثر" },
      ]
    : [
        { icon: "🤖", text: "AI voice & chat agents in Arabic & English" },
        { icon: "📅", text: "Automated booking in under 10 seconds" },
        { icon: "📊", text: "85%+ reduction in no-shows" },
      ];

  const stats = isAr
    ? [
        { n: "١٧+", l: "قطاع" },
        { n: "٦", l: "دول الخليج" },
        { n: "٣٣٣", l: "مسار API" },
      ]
    : [
        { n: "17+", l: "verticals" },
        { n: "6", l: "GCC countries" },
        { n: "333", l: "API routes" },
      ];

  return (
    <div className="flex flex-col md:flex-row min-h-screen" dir={dir}>
      {/* ── Left Brand Panel ──
          overflow-hidden clips the decorative circles.
          No sticky, no h-screen — let flex stretch handle height. */}
      <div className="hidden md:flex md:w-[52%] overflow-hidden relative">
        {/* Background gradient */}
        <div className="absolute inset-0 bg-gradient-to-br from-[#0F9972] via-[#0b8560] to-[#054f3b]" />

        {/* Subtle geometric pattern */}
        <div
          className="absolute inset-0 opacity-[0.06]"
          style={{
            backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%23ffffff'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/svg%3E")`,
          }}
        />

        {/* Decorative circles */}
        <div className="absolute -top-20 -right-20 w-80 h-80 rounded-full bg-white/[0.05]" />
        <div className="absolute -bottom-16 -left-16 w-64 h-64 rounded-full bg-white/[0.05]" />
        <div className="absolute bottom-1/3 -right-10 w-44 h-44 rounded-full bg-white/[0.04]" />

        {/* Content — min-h-screen so it fills the panel */}
        <div className="relative z-10 flex flex-col justify-between p-14 w-full min-h-screen">
          <BrandLogo href={`/${lang}`} size="lg" tone="light" />

          <div className="space-y-10">
            <div className="space-y-4">
              <h1 className="text-[2.6rem] font-bold text-white leading-[1.15] tracking-tight">
                {isAr ? (
                  <>
                    حجوزات ذكية
                    <br />
                    للمنطقة العربية
                  </>
                ) : (
                  <>
                    AI-powered appointments
                    <br />
                    for the GCC region
                  </>
                )}
              </h1>
              <p className="text-[#a7f3d0] text-[1.05rem] leading-relaxed max-w-xs">
                {isAr
                  ? "منصة واحدة لإدارة مواعيد عملائك، التواصل معهم، وتنمية أعمالك."
                  : "One platform to manage bookings, communicate with clients, and grow your business."}
              </p>
            </div>

            <ul className="space-y-4">
              {features.map((f, i) => (
                <li key={i} className="flex items-start gap-3.5">
                  <span className="w-10 h-10 rounded-xl bg-white/15 flex items-center justify-center text-[1.1rem] shrink-0">
                    {f.icon}
                  </span>
                  <span className="text-white/85 text-[0.9rem] leading-snug pt-2">
                    {f.text}
                  </span>
                </li>
              ))}
            </ul>

            <div className="grid grid-cols-3 gap-4 pt-6 border-t border-white/15">
              {stats.map((s, i) => (
                <div key={i} className="text-center">
                  <div className="text-2xl font-bold text-white tracking-tight">
                    {s.n}
                  </div>
                  <div className="text-[0.7rem] text-white/55 mt-0.5 uppercase tracking-wide">
                    {s.l}
                  </div>
                </div>
              ))}
            </div>
          </div>

          <p className="text-white/35 text-xs">
            {isAr ? "موعدي © ٢٠٢٦" : "© 2026 Mawidi · Made for the GCC"}
          </p>
        </div>
      </div>

      {/* Right Form Panel */}
      <div className="relative flex-1 overflow-hidden bg-[#EEF2F6] px-6 py-10 md:min-h-screen md:px-14 md:py-12">
        <div className="pointer-events-none absolute inset-x-0 top-0 h-48 bg-gradient-to-b from-white/70 to-transparent" />
        <div className="pointer-events-none absolute -right-20 top-24 h-64 w-64 rounded-full bg-[#0F9972]/10 blur-3xl" />
        <div className="pointer-events-none absolute -left-20 bottom-20 h-72 w-72 rounded-full bg-cyan-200/20 blur-3xl" />

        <div className="relative mx-auto flex min-h-full w-full max-w-[29rem] flex-col justify-center">
          <div className="mb-10">
            <div className="mb-6 flex items-center justify-between gap-4">
              <AuthBackButton fallbackHref={`/${lang}`} isAr={isAr} />
              <div className="md:hidden">
                <BrandLogo href={`/${lang}`} size="sm" />
              </div>
            </div>
            <p className="text-[0.68rem] font-semibold uppercase tracking-[0.22em] text-[#0F9972]">
              {isAr ? "تسجيل الدخول" : "Client Login"}
            </p>
            <h2 className="mt-2 text-[2.2rem] font-bold leading-[1.08] tracking-tight text-slate-900">
              {isAr ? "مرحباً بعودتك" : "Welcome back"}
            </h2>
            <p className="mt-2 text-[0.96rem] leading-relaxed text-slate-600">
              {isAr
                ? "سجّل الدخول للوصول إلى لوحة التحكم"
                : "Sign in to access your dashboard"}
            </p>
          </div>

          {/* Render Clerk only on client to prevent hydration mismatch */}
          {mounted && !isSignedIn ? (
            <SignIn
              forceRedirectUrl={redirectTarget}
              fallbackRedirectUrl={redirectTarget}
              signUpUrl={`/${lang}/clerk-signup`}
              appearance={{
                layout: {
                  logoPlacement: "none",
                  socialButtonsVariant: "blockButton",
                  socialButtonsPlacement: "top",
                },
                variables: {
                  colorPrimary: "#0F9972",
                  colorText: "#1e293b",
                  colorTextSecondary: "#64748b",
                  colorBackground: "#ffffff",
                  colorInputBackground: "#f8fafc",
                  colorInputText: "#1e293b",
                  borderRadius: "0.875rem",
                  fontFamily: isAr
                    ? "var(--font-ar), Cairo, system-ui"
                    : "var(--font-en), Inter, system-ui",
                },
                elements: {
                  rootBox: "w-full",
                  cardBox: "w-full",
                  card: "!w-full !rounded-[1.3rem] !border !border-slate-200/80 !bg-white !p-6 sm:!p-7 !shadow-[0_28px_48px_-32px_rgba(15,23,42,0.55)]",
                  main: "!gap-5",
                  header: "hidden",
                  formFieldLabel:
                    "!text-[0.78rem] !font-medium !text-slate-700",
                  formFieldInput:
                    "!h-11 !rounded-xl !border-slate-300/90 !bg-slate-50 focus:!ring-2 focus:!ring-[#0F9972]/20 focus:!border-[#0F9972]",
                  formButtonPrimary:
                    "!h-11 !rounded-xl !bg-gradient-to-r !from-[#0F9972] !to-[#0B7F5E] hover:!from-[#0E8D68] hover:!to-[#0A6D52] !font-semibold !tracking-[0.01em] !shadow-[0_14px_26px_-16px_rgba(15,153,114,0.95)]",
                  socialButtonsBlockButton:
                    "!h-11 !rounded-xl !border-slate-300/90 !bg-white hover:!bg-slate-50 transition-colors",
                  socialButtonsBlockButtonText: "!text-slate-700 !font-medium",
                  dividerLine: "!bg-slate-200",
                  dividerText: "!text-slate-400 !text-xs !font-medium",
                  identityPreviewEditButton: "!text-[#0F9972]",
                  footerActionLink: "!text-[#0F9972] hover:underline",
                  footer: "hidden",
                },
              }}
            />
          ) : !mounted ? (
            <div className="w-full rounded-[1.3rem] border border-slate-200/80 bg-white p-6 sm:p-7 shadow-[0_28px_48px_-32px_rgba(15,23,42,0.55)] animate-pulse">
              <div className="space-y-4">
                <div className="h-11 rounded-xl bg-slate-100" />
                <div className="h-11 rounded-xl bg-slate-100" />
                <div className="h-11 rounded-xl bg-slate-100" />
                <div className="h-px bg-slate-200" />
                <div className="h-11 rounded-xl bg-slate-100" />
                <div className="h-11 rounded-xl bg-slate-100" />
                <div className="h-11 rounded-xl bg-[#0F9972]/20" />
              </div>
            </div>
          ) : (
            <div className="w-full rounded-[1.3rem] border border-slate-200/80 bg-white p-6 sm:p-7 shadow-[0_28px_48px_-32px_rgba(15,23,42,0.55)] text-center py-12">
              <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-[#0F9972] border-t-transparent" />
              <p className="mt-4 text-sm text-slate-600">
                {isAr
                  ? "جارٍ التحويل إلى لوحة التحكم..."
                  : "Redirecting to dashboard..."}
              </p>
            </div>
          )}

          <p className="mt-7 text-center text-sm text-slate-600">
            {isAr ? "ليس لديك حساب؟" : "Don't have an account?"}{" "}
            <Link
              href={`/${lang}/clerk-signup`}
              className="font-semibold text-[#0F9972] hover:underline"
            >
              {isAr ? "سجّل مجاناً" : "Sign up free"}
            </Link>
          </p>

          <div className="mt-4 flex items-center justify-center gap-4 text-xs text-slate-400">
            <Link
              href={`/${lang}/privacy`}
              className="transition-colors hover:text-[#0F9972]"
            >
              {isAr ? "الخصوصية" : "Privacy"}
            </Link>
            <span>·</span>
            <Link
              href={`/${lang}/terms`}
              className="transition-colors hover:text-[#0F9972]"
            >
              {isAr ? "الشروط" : "Terms"}
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
