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

type InvMode = "signup" | "otp" | "pending" | "approved" | "rejected";

const CITIES = ["الرياض", "جدة", "الدمام", "مكة المكرمة", "المدينة المنورة"];
const COUNTRIES = ["السعودية", "الإمارات", "الكويت", "البحرين", "قطر"];

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(" ");
}

/** Centered state card wrapper (max 480px) used across the investor auth flow. */
function Card({ children }: { children: ReactNode }) {
  return (
    <div className="min-h-[calc(100vh-260px)] flex items-center bg-background-50">
      <Container className="py-16">
        <div className="w-full max-w-[480px] mx-auto bg-background-100 border border-background-200 rounded-[24px] p-8 md:p-10 animate-fade-up">
          {children}
        </div>
      </Container>
    </div>
  );
}

function Brand() {
  return (
    <div className="w-14 h-14 rounded-[18px] bg-primary-500 flex items-center justify-center mx-auto mb-6">
      <BrandMark className="w-8 h-5 text-background-50" />
    </div>
  );
}

export default function InvAuth() {
  const { params, jump, navigate } = useWeb();
  const initial = (params.state as InvMode) ?? (params.mode === "otp" ? "otp" : "signup");
  const [mode, setMode] = useState<InvMode>(initial);
  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [type, setType] = useState("");
  const [city, setCity] = useState("");
  const [country, setCountry] = useState("");
  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{8,9}$/.test(phoneDigits);
  const formValid = fullName.trim().length > 2 && phoneValid && !!type && !!city && !!country;

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

  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();
  };

  if (mode === "otp") {
    return (
      <Card>
        <Brand />
        <h1 className="text-[23px] font-bold text-foreground-950 font-heading text-center">أدخل كود التحقق</h1>
        <p className="text-[13.5px] text-foreground-600 mt-3 text-center leading-relaxed">
          أرسلنا كود التحقق المكوّن من 4 أرقام إلى الرقم
        </p>
        <p dir="ltr" className="text-[15px] font-bold text-foreground-950 mt-1.5 text-center">
          +966 {formatSaPhone(phone)}
        </p>
        <div className="flex items-center justify-center gap-3 mt-7" 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-50 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 justify-center gap-1">
            <i className="ri-error-warning-line text-[14px] leading-none" />
            {error}
          </p>
        )}
        <p className="text-[13px] text-foreground-600 mt-6 text-center">
          {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" disabled={code.some((c) => !c)} onClick={() => (code.every((c) => c !== "") ? setMode("pending") : setError("الكود غير صحيح، حاول مرة أخرى."))}>
          تأكيد
        </WBtn>
        <div className="text-center mt-5">
          <button type="button" onClick={() => setMode("signup")} className="text-[13px] font-semibold text-foreground-950 underline underline-offset-4 cursor-pointer whitespace-nowrap">
            تغيير البيانات
          </button>
        </div>
      </Card>
    );
  }

  if (mode === "pending") {
    return (
      <Card>
        <span className="w-20 h-20 rounded-full bg-secondary-100 text-secondary-900 flex items-center justify-center mx-auto mb-6">
          <i className="ri-time-line text-[42px] leading-none" />
        </span>
        <h1 className="text-[23px] font-bold text-foreground-950 font-heading text-center">حسابك قيد المراجعة</h1>
        <p className="text-[14px] text-foreground-600 mt-3 leading-relaxed text-center">
          استلمنا بياناتك بنجاح، وسيتم مراجعة طلب تسجيلك كجهة استثمارية. سيصلك إشعار عند اعتماد الحساب.
        </p>
        <div className="mt-6 space-y-3">
          <WBtn full onClick={() => setMode("approved")}>
            محاكاة: تمت الموافقة
          </WBtn>
          <WBtn full variant="secondary" onClick={() => setMode("rejected")}>
            محاكاة: تم الرفض
          </WBtn>
        </div>
      </Card>
    );
  }

  if (mode === "approved") {
    return (
      <Card>
        <span className="w-20 h-20 rounded-full bg-accent-100 text-accent-800 flex items-center justify-center mx-auto mb-6">
          <i className="ri-checkbox-circle-line text-[44px] leading-none" />
        </span>
        <h1 className="text-[23px] font-bold text-foreground-950 font-heading text-center">تمت الموافقة على حسابك</h1>
        <p className="text-[14px] text-foreground-600 mt-3 leading-relaxed text-center">
          مرحبًا بك في منصة دشن. أكمل ملفك الاستثماري لتبدأ باكتشاف الفرص وتقديم العروض.
        </p>
        <WBtn full size="lg" className="w-full mt-7" onClick={() => navigate("invProfileSetup")}>
          استكمال الملف الاستثماري
        </WBtn>
      </Card>
    );
  }

  if (mode === "rejected") {
    return (
      <Card>
        <span className="w-20 h-20 rounded-full bg-danger-100 text-danger-700 flex items-center justify-center mx-auto mb-6">
          <i className="ri-close-circle-line text-[44px] leading-none" />
        </span>
        <h1 className="text-[23px] font-bold text-foreground-950 font-heading text-center">تم رفض طلب التسجيل</h1>
        <p className="text-[14px] text-foreground-600 mt-3 leading-relaxed text-center">
          لم نتمكن من اعتماد بياناتك. يمكنك مراجعة البيانات وإعادة إرسال الطلب.
        </p>
        <div className="mt-5 rounded-[16px] bg-danger-50 border border-danger-200 p-4 text-start">
          <p className="text-[12px] font-semibold text-danger-700 mb-1">سبب الرفض</p>
          <p className="text-[13px] text-foreground-700 leading-relaxed">
            البيانات غير مطابقة للوثائق الرسمية. يرجى التأكد من الاسم ونوع المستثمر وإعادة المحاولة.
          </p>
        </div>
        <WBtn full size="lg" className="w-full mt-6" onClick={() => setMode("signup")}>
          إعادة إرسال الطلب
        </WBtn>
      </Card>
    );
  }

  /* signup */
  return (
    <div className="min-h-[calc(100vh-260px)] flex items-center bg-background-50">
      <Container className="py-14">
        <div className="w-full max-w-[520px] mx-auto animate-fade-up">
          <div className="text-center mb-8">
            <div className="w-14 h-14 rounded-[18px] bg-primary-500 flex items-center justify-center mx-auto mb-5">
              <i className="ri-line-chart-line text-[26px] text-background-50 leading-none" />
            </div>
            <h1 className="text-[27px] md:text-[30px] font-bold text-foreground-950 font-heading">إنشاء حساب مستثمر</h1>
            <p className="text-[14px] text-foreground-600 mt-2.5 leading-relaxed">
              أدخل بياناتك للانضمام إلى منصة دشن واكتشاف الفرص الاستثمارية.
            </p>
          </div>

          <div className="bg-background-100 border border-background-200 rounded-[24px] p-7 md:p-9">
            <div className="space-y-4">
              <Labelled label="الاسم الكامل">
                <WInput value={fullName} onChange={setFullName} placeholder="مثال: فيصل بن تركي الحربي" />
              </Labelled>

              <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>

              <Labelled label="نوع المستثمر">
                <WSelect value={type} onChange={setType} placeholder="اختر النوع" options={["فرد", "جهة استثمارية"]} />
              </Labelled>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <Labelled label="المدينة">
                  <WSelect value={city} onChange={setCity} placeholder="اختر المدينة" options={CITIES} />
                </Labelled>
                <Labelled label="الدولة">
                  <WSelect value={country} onChange={setCountry} placeholder="اختر الدولة" options={COUNTRIES} />
                </Labelled>
              </div>
            </div>

            <WBtn full size="lg" className="w-full mt-7" disabled={!formValid} onClick={() => setMode("otp")}>
              متابعة
            </WBtn>

            <p className="text-[14px] text-foreground-600 mt-5 text-center">
              لديك حساب بالفعل؟{" "}
              <button type="button" onClick={() => jump("home")} className="font-semibold text-foreground-950 underline underline-offset-4 cursor-pointer whitespace-nowrap">
                سجّل دخول
              </button>
            </p>
          </div>
        </div>
      </Container>
    </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>
  );
}