import { useEffect, useRef, useState, type ReactNode } from "react";
import { useWeb } from "../WebContext";
import { WBtn, WInput, WSelect, cn } from "../WebUI";
import { BrandMark } from "@/components/base/BrandLogo";
import type { WebRole } from "../types";

const ROLE_CARDS: { role: WebRole; title: string; desc: string; icon: string }[] = [
  {
    role: "customer",
    title: "عميل",
    desc: "تصفّح المنشآت والمنتجات واطلب وتفاوض بسهولة",
    icon: "ri-user-3-line",
  },
  {
    role: "business",
    title: "صاحب بيزنس",
    desc: "دشّن منشأتك واعرض منتجاتك وفرصك الاستثمارية",
    icon: "ri-store-2-line",
  },
  {
    role: "investor",
    title: "مستثمر",
    desc: "اكتشف الفرص الاستثمارية الواعدة وقدّم عروضك",
    icon: "ri-line-chart-line",
  },
];

/* ------------------------------------------------------------------ */
/* Brand panel (shared by account-type & login)                        */
/* ------------------------------------------------------------------ */
function BrandCard({ title, subtitle }: { title: ReactNode; subtitle: string }) {
  return (
    <div className="relative h-full w-full bg-background-100 border border-background-200 rounded-[32px] p-10 xl:p-14 overflow-hidden">
      <div className="pointer-events-none absolute -top-24 -left-24 w-72 h-72 rounded-full bg-accent-50" />
      <div className="relative">
        <div className="w-16 h-16 rounded-[20px] bg-primary-500 flex items-center justify-center mb-8">
          <BrandMark className="w-9 h-6 text-background-50" />
        </div>
        <h1 className="font-heading text-[30px] xl:text-[40px] font-bold text-foreground-950 leading-[1.3]">{title}</h1>
        <p className="text-[15px] xl:text-[16px] text-foreground-600 mt-6 leading-relaxed max-w-[440px]">{subtitle}</p>
      </div>
    </div>
  );
}

export function AuthSelect() {
  const { navigate, jump } = useWeb();

  return (
    <div className="min-h-[calc(100vh-72px)] flex items-center bg-background-50">
      <div className="w-full max-w-[1200px] mx-auto px-4 md:px-8 py-16">
        <div className="flex flex-col lg:flex-row lg:items-center gap-10 xl:gap-20">
          <div className="w-full lg:flex-1">
            <BrandCard
              title={
                <>
                  المنصة الرقمية الأولى
                  <br />
                  لتدشين المشاريع والعلامات التجارية
                </>
              }
              subtitle="جمعنا لك المنشآت والمنتجات والفرص الاستثمارية في مكان واحد داخل المملكة العربية السعودية."
            />
          </div>

          <div className="w-full max-w-[480px] mx-auto lg:mx-0 lg:w-[480px] lg:shrink-0">
            <button
              type="button"
              onClick={() => jump("home")}
              className="w-full h-[54px] rounded-[16px] bg-primary-500 text-background-50 text-[16px] font-semibold flex items-center justify-center gap-2 hover:bg-primary-600 transition-colors cursor-pointer whitespace-nowrap"
            >
              <i className="ri-compass-3-line text-[20px] leading-none" />
              تصفح كزائر
            </button>

            <div className="flex items-center gap-4 my-7">
              <span className="flex-1 h-px bg-background-200" />
              <span className="text-[13px] text-foreground-500">أو سجّل حسابك</span>
              <span className="flex-1 h-px bg-background-200" />
            </div>

            <div className="space-y-3">
              {ROLE_CARDS.map((r) => (
                <button
                  key={r.role}
                  type="button"
                  onClick={() => navigate("auth", { mode: "signup", role: r.role })}
                  className="w-full min-h-[96px] bg-background-100 border border-background-200 rounded-[20px] p-5 flex items-center gap-4 text-right hover:border-foreground-300 transition-colors cursor-pointer"
                >
                  <span className="w-12 h-12 rounded-[14px] bg-background-200 flex items-center justify-center shrink-0">
                    <i className={`${r.icon} text-[24px] text-foreground-950 leading-none`} />
                  </span>
                  <span className="flex-1 min-w-0 text-right">
                    <span className="block text-[16px] font-semibold text-foreground-950">{r.title}</span>
                    <span className="block text-[13px] text-foreground-600 mt-0.5 leading-snug">{r.desc}</span>
                  </span>
                  <i className="ri-arrow-left-s-line text-[22px] text-foreground-400 leading-none shrink-0" />
                </button>
              ))}
            </div>

            <div className="text-center text-[14px] text-foreground-600 mt-8">
              لديك حساب بالفعل؟{" "}
              <button
                type="button"
                onClick={() => navigate("auth", { mode: "login", role: "customer" })}
                className="font-semibold text-foreground-950 underline underline-offset-4 cursor-pointer whitespace-nowrap"
              >
                سجّل دخول
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function formatSaPhone(p: string): string {
  const d = p.replace(/\D/g, "");
  if (!d) return "5X XXX XXXX";
  const a = d.slice(0, 2);
  const b = d.slice(2, 5);
  const c = d.slice(5, 9);
  return [a, b, c].filter(Boolean).join(" ");
}

export function AuthCard() {
  const { t, params, completeAuth, navigate } = useWeb();
  const role: WebRole = params.role ?? "customer";
  const [flow, setFlow] = useState<"login" | "signup">(params.mode === "signup" ? "signup" : "login");
  const [step, setStep] = useState<"form" | "otp">(params.mode === "otp" ? "otp" : "form");
  const [submitting, setSubmitting] = useState(false);
  const isSignup = flow === "signup";
  const roleLabel =
    role === "business" ? t("roleBusiness") : role === "investor" ? t("roleInvestor") : t("roleCustomer");
  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [bizName, setBizName] = useState("");
  const [city, setCity] = useState("");
  const [investorType, setInvestorType] = useState("");
  const [location, setLocation] = useState<{ label: string; query: string } | null>(null);
  const [locating, setLocating] = useState(false);
  const [code, setCode] = useState(["", "", "", ""]);
  const [error, setError] = useState("");
  const [count, setCount] = useState(42);
  const refs = useRef<Array<HTMLInputElement | null>>([]);

  const phoneDigits = phone.replace(/\D/g, "");
  const phoneValid = /^5\d{9}$/.test(phoneDigits) || /^5\d{8}$/.test(phoneDigits);
  const formValid = isSignup
    ? fullName.trim().length > 2 &&
      phoneValid &&
      (role === "business"
        ? bizName.trim().length > 1 && !!city
        : role === "investor"
          ? !!investorType && !!city
          : !!location)
    : phoneValid;

  const useCurrentLocation = () => {
    setLocating(true);
    setTimeout(() => {
      setLocation({ label: "الرياض، حي العليا", query: "Olaya, Riyadh, Saudi Arabia" });
      setLocating(false);
    }, 900);
  };

  useEffect(() => {
    if (step !== "otp") return;
    setCount(42);
    const id = setInterval(() => setCount((c) => (c > 0 ? c - 1 : 0)), 1000);
    return () => clearInterval(id);
  }, [step]);

  const switchToLogin = () => {
    setFlow("login");
    setStep("form");
    setError("");
    setSubmitting(false);
    navigate("auth", { mode: "login", role });
  };

  const startOtp = () => {
    if (!formValid) return;
    setError("");
    setCode(["", "", "", ""]);
    setStep("otp");
  };

  const setDigit = (i: number, v: string) => {
    const d = v.replace(/\D/g, "").slice(-1);
    const next = [...code];
    next[i] = d;
    setCode(next);
    setError("");
    if (d && i < 3) refs.current[i + 1]?.focus();
  };

  const confirmOtp = () => {
    if (submitting) return;
    if (!code.every((c) => c !== "")) {
      setError(t("otpError"));
      return;
    }
    setError("");
    setSubmitting(true);
    window.setTimeout(() => {
      completeAuth(role);
    }, 450);
  };

  return (
    <div className="min-h-[calc(100vh-72px)] flex items-center bg-background-50">
      <div className="w-full max-w-[1100px] mx-auto px-4 md:px-8 py-10">
        <div className="flex flex-col lg:flex-row items-stretch gap-6 animate-fade-up">
          <div className="w-full lg:flex-1 lg:min-w-0">
            <BrandCard
              title="مرحبًا بعودتك"
              subtitle="أدخل رقم جوالك وسنرسل لك كود تحقق لتسجيل الدخول والوصول إلى حسابك على منصة دشن."
            />
          </div>

          <div className="w-full lg:w-[440px] lg:shrink-0 bg-background-100 border border-background-200 rounded-[20px] p-10 h-full flex flex-col justify-center">
            {step === "otp" ? (
              <>
                <h1 className="text-[24px] font-bold text-foreground-950 font-heading">أدخل كود التحقق</h1>
                <p className="text-[14px] text-foreground-600 mt-3 leading-relaxed">
                  أرسلنا كود التحقق المكوّن من 4 أرقام إلى الرقم
                </p>
                <p dir="ltr" className="text-[15px] font-bold text-foreground-950 mt-1.5 text-end">
                  +966 {formatSaPhone(phone)}
                </p>

                <div className="flex items-center gap-3 mt-6" dir="ltr">
                  {code.map((c, i) => (
                    <input
                      key={i}
                      ref={(el) => {
                        refs.current[i] = el;
                      }}
                      value={c}
                      inputMode="numeric"
                      maxLength={1}
                      onChange={(e) => setDigit(i, e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === "Backspace" && !code[i] && i > 0) refs.current[i - 1]?.focus();
                      }}
                      className={cn(
                        "w-16 h-16 rounded-[16px] bg-background-100 border text-center text-[26px] font-bold text-foreground-950 outline-none transition-colors",
                        error ? "border-danger-400" : "border-background-200 focus:border-foreground-400",
                      )}
                    />
                  ))}
                </div>

                {error && (
                  <p className="text-[12.5px] text-danger-600 mt-3 flex items-center gap-1">
                    <i className="ri-error-warning-line text-[14px] leading-none" />
                    {error}
                  </p>
                )}

                <p className="text-[13px] text-foreground-600 mt-6">
                  {count > 0 ? (
                    <>
                      إعادة الإرسال خلال{" "}
                      <span dir="ltr" className="font-bold text-foreground-900">00:{String(count).padStart(2, "0")}</span>
                    </>
                  ) : (
                    <button
                      type="button"
                      onClick={() => setCount(42)}
                      className="font-semibold text-foreground-950 underline underline-offset-4 cursor-pointer"
                    >
                      إعادة الإرسال
                    </button>
                  )}
                </p>

                <WBtn
                  full
                  size="lg"
                  className="w-full mt-6"
                  onClick={confirmOtp}
                  disabled={code.some((c) => !c) || submitting}
                >
                  {submitting ? (
                    <span className="inline-flex items-center gap-2 whitespace-nowrap">
                      <i className="ri-loader-4-line text-[18px] leading-none animate-spin" />
                      جارٍ التحقق...
                    </span>
                  ) : (
                    "تأكيد"
                  )}
                </WBtn>

                <div className="text-center mt-5">
                  <button
                    type="button"
                    onClick={() => {
                      setStep("form");
                      setError("");
                    }}
                    className="text-[13px] font-semibold text-foreground-950 underline underline-offset-4 cursor-pointer whitespace-nowrap"
                  >
                    تغيير الرقم
                  </button>
                </div>
              </>
            ) : (
              <>
                {isSignup ? (
                  <h1 className="text-[24px] font-bold text-foreground-950 font-heading mb-6">{`إنشاء حساب ${roleLabel}`}</h1>
                ) : (
                  <div className="mb-6">
                    <h1 className="text-[24px] font-bold text-foreground-950 font-heading">تسجيل الدخول</h1>
                    <p className="text-[13.5px] text-foreground-600 mt-2 leading-relaxed">
                      {role === "customer"
                        ? "أدخل رقم جوالك للوصول إلى حسابك ومتابعة طلباتك."
                        : `أدخل رقم جوالك للوصول إلى حسابك كـ${roleLabel}.`}
                    </p>
                  </div>
                )}

                <div className="space-y-4">
                  {isSignup && (
                    <Labelled label={t("fullName")}>
                      <WInput value={fullName} onChange={setFullName} placeholder="مثال: عبدالله المطيري" />
                    </Labelled>
                  )}

                  <div>
                    <Labelled label="رقم الجوال">
                      <div
                        className="flex items-center h-12 rounded-[16px] bg-background-50 border border-background-200 focus-within:border-foreground-400 transition-colors overflow-hidden"
                        dir="ltr"
                      >
                        <span className="h-full px-3.5 flex items-center gap-1.5 bg-background-200 text-foreground-800 text-[14px] font-semibold shrink-0">
                          <span className="text-[16px] leading-none">🇸🇦</span>
                          +966
                        </span>
                        <input
                          value={phone}
                          inputMode="numeric"
                          onChange={(e) => setPhone(e.target.value.replace(/\D/g, "").slice(0, 9))}
                          placeholder="5XXXXXXXX"
                          className="flex-1 min-w-0 h-full px-3.5 bg-transparent text-[14px] text-foreground-950 placeholder:text-foreground-500 outline-none font-body"
                        />
                      </div>
                    </Labelled>
                    {!isSignup && (
                      <p className="text-[12.5px] text-foreground-500 mt-2">سنتحقق من رقمك عبر كود يُرسل برسالة نصية.</p>
                    )}
                  </div>

                  {isSignup && role === "customer" && (
                    <div>
                      <span className="block text-[13px] font-semibold text-foreground-800 mb-1.5">تحديد الموقع</span>
                      <div className="relative w-full h-[190px] rounded-[16px] overflow-hidden border border-background-200 bg-background-100">
                        {location ? (
                          <>
                            <iframe
                              title="موقعك المحدد"
                              className="absolute inset-0 w-full h-full border-0"
                              src={`https://www.google.com/maps?q=${encodeURIComponent(location.query)}&z=14&output=embed`}
                            />
                            <div className="absolute inset-x-0 bottom-0 h-24 bg-gradient-to-t from-foreground-950/60 to-transparent pointer-events-none" />
                            <div className="absolute inset-x-3 bottom-3 flex items-center gap-2">
                              <div className="flex-1 min-w-0 h-10 rounded-full bg-background-100/95 backdrop-blur flex items-center gap-2 px-3.5">
                                <i className="ri-map-pin-2-fill text-[16px] text-foreground-950 leading-none shrink-0" />
                                <span className="text-[12.5px] font-medium text-foreground-950 truncate">{location.label}</span>
                              </div>
                              <button
                                type="button"
                                onClick={useCurrentLocation}
                                aria-label="تحديث الموقع"
                                className="w-10 h-10 rounded-full bg-background-100/95 backdrop-blur flex items-center justify-center text-foreground-950 cursor-pointer shrink-0"
                              >
                                <i className={`${locating ? "ri-loader-4-line animate-spin" : "ri-refresh-line"} text-[17px] leading-none`} />
                              </button>
                            </div>
                          </>
                        ) : (
                          <button
                            type="button"
                            onClick={useCurrentLocation}
                            className="w-full h-full flex flex-col items-center justify-center gap-2 cursor-pointer transition-colors hover:bg-background-200/60"
                          >
                            <div className="w-12 h-12 rounded-full bg-background-200 flex items-center justify-center">
                              <i
                                className={`${
                                  locating ? "ri-loader-4-line animate-spin text-[20px]" : "ri-map-pin-2-line text-[24px]"
                                } text-foreground-700 leading-none`}
                              />
                            </div>
                            <span className="text-[14px] font-medium text-foreground-900">
                              {locating ? "جاري تحديد الموقع..." : "استخدم موقعي الحالي"}
                            </span>
                            <span className="text-[12px] text-foreground-500">اضغط لتحديد موقعك تلقائيًا</span>
                          </button>
                        )}
                      </div>
                      <button
                        type="button"
                        onClick={() => setLocation({ label: "جدة، حي الروضة", query: "Al Rawdah, Jeddah, Saudi Arabia" })}
                        className="mt-2 text-[12px] text-foreground-600 underline underline-offset-2 cursor-pointer"
                      >
                        أو اختر الموقع من الخريطة
                      </button>
                    </div>
                  )}

                  {isSignup && role === "business" && (
                    <>
                      <Labelled label="اسم النشاط التجاري">
                        <WInput value={bizName} onChange={setBizName} placeholder="مثال: متجر النخبة" />
                      </Labelled>
                      <Labelled label={t("city")}>
                        <WSelect value={city} onChange={setCity} placeholder="اختر المدينة" options={["الرياض", "جدة", "الدمام", "مكة المكرمة", "المدينة المنورة"]} />
                      </Labelled>
                    </>
                  )}

                  {isSignup && role === "investor" && (
                    <>
                      <Labelled label="نوع المستثمر">
                        <WSelect value={investorType} onChange={setInvestorType} placeholder="اختر النوع" options={["فرد", "جهة استثمارية"]} />
                      </Labelled>
                      <Labelled label={t("city")}>
                        <WSelect value={city} onChange={setCity} placeholder="اختر المدينة" options={["الرياض", "جدة", "الدمام"]} />
                      </Labelled>
                    </>
                  )}
                </div>

                <WBtn full size="lg" className="w-full mt-6" onClick={startOtp} disabled={!formValid}>
                  {isSignup ? "متابعة" : "تسجيل الدخول"}
                </WBtn>

                <p className="text-[14px] text-foreground-600 mt-5 text-center">
                  {isSignup ? "لديك حساب بالفعل؟" : "ليس لديك حساب؟"}{" "}
                  <button
                    type="button"
                    onClick={() => (isSignup ? switchToLogin() : navigate("authSelect"))}
                    className="font-semibold text-foreground-950 underline underline-offset-4 cursor-pointer whitespace-nowrap"
                  >
                    {isSignup ? "سجّل دخول" : "إنشاء حساب"}
                  </button>
                </p>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function Labelled({ label, children }: { label: string; children: ReactNode }) {
  return (
    <label className="block">
      <span className="block text-[13px] font-semibold text-foreground-800 mb-1.5">{label}</span>
      {children}
    </label>
  );
}