import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { useProductStore } from "@/pages/product/store";
import { BackHeader, Btn, LogoMark, cn } from "@/pages/app/components/ui";
import { Field, TextInput } from "@/pages/app/components/bo/BoUI";

export default function BizLogin({ variant }: { variant?: string }) {
  const { goBack, navigate } = useApp();
  const { bizSignup } = useProductStore();
  const showError = variant === "error";

  const [mode, setMode] = useState<"login" | "recover">("login");
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [remember, setRemember] = useState(true);
  const [error, setError] = useState(
    showError ? "رقم الجوال أو كلمة المرور غير صحيحة. حاول مرة أخرى." : "",
  );
  const [recoverPhone, setRecoverPhone] = useState("");
  const [recoverSent, setRecoverSent] = useState(false);

  const canSubmit = phone.length >= 5 && password.length >= 4;

  const submit = () => {
    if (!phone || !password) {
      setError("أدخل رقم الجوال وكلمة المرور للمتابعة.");
      return;
    }
    if (!canSubmit) {
      setError("تأكد من صحة رقم الجوال وكلمة المرور.");
      return;
    }
    setError("");
    // The account state decides where the owner lands after sign-in.
    if (bizSignup.status === "rejected") {
      setError("طلب حساب منشأتك مرفوض. عدّل بياناتك وأعد التقديم من صفحة التسجيل.");
      return;
    }
    if (bizSignup.status === "review" || bizSignup.status === "approved" || bizSignup.status === "setup") {
      navigate("bizPending");
      return;
    }
    navigate("bizDashboard");
  };

  const sendRecover = () => {
    if (recoverPhone.length < 5) {
      setError("أدخل رقم جوال صحيح مرتبط بحساب منشأتك.");
      return;
    }
    setError("");
    setRecoverSent(true);
  };

  return (
    <div className="min-h-full flex flex-col bg-background-50">
      <BackHeader title={mode === "login" ? "تسجيل الدخول" : "استعادة كلمة المرور"} onBack={goBack} />

      <div className="flex-1 px-5 pt-6 pb-8">
        <div className="flex flex-col items-center text-center mb-6">
          <div className="w-14 h-14 rounded-[18px] bg-primary-500 flex items-center justify-center mb-3.5">
            <LogoMark className="text-[19px] text-background-50" />
          </div>
          <h1 className="text-[21px] font-bold text-foreground-950">
            {mode === "login" ? "مرحبًا بعودتك" : "استعادة كلمة المرور"}
          </h1>
          <p className="text-[13px] text-foreground-600 leading-relaxed max-w-[290px] mt-1.5">
            {mode === "login"
              ? "سجّل الدخول للوصول إلى لوحة تحكم منشأتك وطلباتك وفرصك الاستثمارية."
              : "أدخل رقم الجوال المسجل في حساب منشأتك لإرسال رمز التحقق."}
          </p>
        </div>

        {mode === "login" ? (
          <>
            <div className="space-y-4">
              <Field label="رقم الجوال أو البريد الإلكتروني" required>
                <TextInput
                  value={phone}
                  onChange={(v) => setPhone(v)}
                  placeholder="5XXXXXXXX"
                  prefix="+966"
                  dir="ltr"
                />
              </Field>

              <Field label="كلمة المرور" required>
                <div className="relative">
                  <input
                    type={showPassword ? "text" : "password"}
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="••••••••"
                    className="w-full h-[48px] px-4 pe-12 rounded-[13px] bg-background-100 border border-background-200 text-[13.5px] text-foreground-950 placeholder:text-foreground-500 outline-none focus:border-foreground-400 transition-colors font-body"
                  />
                  <button
                    type="button"
                    aria-label={showPassword ? "إخفاء كلمة المرور" : "إظهار كلمة المرور"}
                    onClick={() => setShowPassword((v) => !v)}
                    className="absolute end-2.5 top-1/2 -translate-y-1/2 w-9 h-9 rounded-full flex items-center justify-center text-foreground-500 cursor-pointer"
                  >
                    <i className={cn(showPassword ? "ri-eye-off-line" : "ri-eye-line", "text-[18px] leading-none")} />
                  </button>
                </div>
              </Field>
            </div>

            <div className="flex items-center justify-between gap-3 mt-4">
              <button
                type="button"
                onClick={() => setRemember((v) => !v)}
                className="flex items-center gap-2 text-[12.5px] text-foreground-700 cursor-pointer"
              >
                <span
                  className={cn(
                    "w-[18px] h-[18px] rounded-[6px] border flex items-center justify-center shrink-0 transition-colors",
                    remember
                      ? "bg-primary-500 border-primary-500 text-background-50"
                      : "border-background-300 bg-background-100",
                  )}
                >
                  {remember && <i className="ri-check-line text-[13px] leading-none" />}
                </span>
                تذكرني
              </button>
              <button
                type="button"
                onClick={() => {
                  setError("");
                  setRecoverSent(false);
                  setMode("recover");
                }}
                className="text-[12.5px] font-semibold text-foreground-950 cursor-pointer"
              >
                نسيت كلمة المرور؟
              </button>
            </div>

            {error && (
              <div className="mt-4 rounded-[13px] bg-danger-100 border border-danger-300 px-4 py-3 text-[12.5px] text-danger-700 flex items-start gap-2">
                <i className="ri-error-warning-line text-[16px] leading-none mt-0.5 shrink-0" />
                <span className="leading-relaxed">{error}</span>
              </div>
            )}

            <Btn full className="mt-5" disabled={!phone || !password} onClick={submit}>
              تسجيل الدخول
            </Btn>

            <div className="flex items-center gap-3 my-5">
              <span className="flex-1 h-px bg-background-200" />
              <span className="text-[11.5px] text-foreground-500">أو</span>
              <span className="flex-1 h-px bg-background-200" />
            </div>

            <button
              type="button"
              onClick={() => navigate("bizOtp")}
              className="w-full h-[50px] rounded-[14px] border border-background-300 bg-background-100 text-[14px] font-semibold text-foreground-900 flex items-center justify-center gap-2 cursor-pointer"
            >
              <i className="ri-shield-keyhole-line text-[18px] leading-none" />
              الدخول برمز تحقق (OTP)
            </button>

            <p className="text-center text-[13px] text-foreground-600 mt-6">
              ليس لديك حساب؟{" "}
              <button
                type="button"
                onClick={() => navigate("bizRegister")}
                className="font-semibold text-foreground-950 cursor-pointer"
              >
                سجّل منشأتك
              </button>
            </p>
          </>
        ) : (
          <>
            {recoverSent ? (
              <div className="rounded-[16px] bg-accent-100 border border-accent-200 p-4 flex items-start gap-3">
                <span className="w-10 h-10 rounded-full bg-accent-200 text-accent-800 flex items-center justify-center shrink-0">
                  <i className="ri-check-line text-[19px] leading-none" />
                </span>
                <div className="min-w-0">
                  <p className="text-[13.5px] font-semibold text-accent-900">تم إرسال رمز التحقق</p>
                  <p className="text-[12px] text-accent-800 mt-1 leading-relaxed">
                    أرسلنا رمزًا مكوّنًا من 4 أرقام إلى <span dir="ltr">{recoverPhone}</span>.
                  </p>
                </div>
              </div>
            ) : (
              <Field label="رقم الجوال المسجل" required hint="نرسل الرمز إلى رقم الجوال المرتبط بحساب المنشأة.">
                <TextInput
                  value={recoverPhone}
                  onChange={(v) => setRecoverPhone(v.replace(/\D/g, "").slice(0, 9))}
                  placeholder="5XXXXXXXX"
                  prefix="+966"
                  dir="ltr"
                />
              </Field>
            )}

            {error && (
              <div className="mt-4 rounded-[13px] bg-danger-100 border border-danger-300 px-4 py-3 text-[12.5px] text-danger-700 flex items-start gap-2">
                <i className="ri-error-warning-line text-[16px] leading-none mt-0.5 shrink-0" />
                <span className="leading-relaxed">{error}</span>
              </div>
            )}

            <Btn
              full
              className="mt-5"
              onClick={() => (recoverSent ? navigate("bizOtp") : sendRecover())}
            >
              {recoverSent ? "إدخال رمز التحقق" : "إرسال رمز التحقق"}
            </Btn>

            <button
              type="button"
              onClick={() => {
                setMode("login");
                setError("");
                setRecoverSent(false);
              }}
              className="w-full text-center text-[13px] font-semibold text-foreground-700 mt-5 cursor-pointer"
            >
              العودة لتسجيل الدخول
            </button>
          </>
        )}
      </div>
    </div>
  );
}