import { useState } from "react";
import { useApp } from "../AppContext";
import { BackHeader, Btn } from "../components/ui";

type LocationValue = {
  label: string;
  query: string;
};

export default function Signup() {
  const { goBack, navigate, startAuth } = useApp();
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [location, setLocation] = useState<LocationValue | null>(null);
  const [locating, setLocating] = useState(false);
  const [phoneTaken, setPhoneTaken] = useState(false);

  const valid = name.trim() && phone.trim().length >= 9 && location;

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

  const submit = () => {
    if (!valid) return;
    if (phoneTaken) return;
    navigate("otp");
  };

  return (
    <div className="min-h-full flex flex-col bg-background-50">
      <BackHeader title="إنشاء حساب عميل" onBack={goBack} />

      <div className="flex-1 px-5 pt-5">
        <p className="text-[13px] text-foreground-600 leading-relaxed mb-6">
          أدخل بياناتك الأساسية لإنشاء حسابك في منصة دشن، وسنرسل لك كود تحقق على جوالك. يتم تفعيل الحساب فورًا بعد التحقق.
        </p>

        <div className="space-y-5">
          <div>
            <label className="text-[13px] font-semibold text-foreground-900 block mb-2">الاسم الكامل</label>
            <input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="مثال: عبدالله الحربي"
              className="w-full h-[52px] rounded-[14px] bg-background-100 border border-background-200 px-4 text-[14px] text-foreground-950 placeholder:text-foreground-500 outline-none focus:border-foreground-400 transition-colors font-body"
            />
          </div>

          <div>
            <label className="text-[13px] font-semibold text-foreground-900 block mb-2">رقم الجوال</label>
            <div
              className={`flex items-center h-[52px] rounded-[14px] bg-background-100 border transition-colors overflow-hidden ${
                phoneTaken ? "border-danger-500" : "border-background-200 focus-within:border-foreground-400"
              }`}
              dir="ltr"
            >
              <span className="px-4 h-full flex items-center gap-1.5 bg-background-200 text-[14px] font-semibold text-foreground-900 border-l border-background-300 shrink-0">
                <span className="text-[15px]">🇸🇦</span>
                +966
              </span>
              <input
                value={phone}
                onChange={(e) => {
                  setPhone(e.target.value.replace(/\D/g, "").slice(0, 9));
                  setPhoneTaken(false);
                }}
                placeholder="5XXXXXXXX"
                inputMode="numeric"
                className="flex-1 min-w-0 h-full bg-transparent px-4 text-[14px] text-foreground-950 placeholder:text-foreground-500 outline-none font-body tracking-wide"
              />
            </div>
            {phoneTaken && (
              <div className="mt-2 flex items-center justify-between gap-2 animate-fade-in">
                <div className="flex items-center gap-1.5 text-danger-600">
                  <i className="ri-error-warning-line text-[15px] leading-none" />
                  <span className="text-[12px] font-medium">رقم الجوال مسجل مسبقًا</span>
                </div>
                <button
                  type="button"
                  onClick={() => startAuth("login")}
                  className="text-[12px] font-semibold text-foreground-950 underline underline-offset-2 cursor-pointer whitespace-nowrap"
                >
                  تسجيل الدخول
                </button>
              </div>
            )}
            {!phoneTaken && (
              <button
                type="button"
                onClick={() => setPhoneTaken(true)}
                className="mt-2 text-[11px] text-foreground-400 cursor-pointer"
              >
                تجربة حالة: رقم مسجل مسبقًا
              </button>
            )}
          </div>

          <div>
            <label className="text-[13px] font-semibold text-foreground-900 block mb-2">تحديد الموقع</label>
            <div className="relative w-full aspect-square 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-28 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-11 rounded-full bg-background-100/95 backdrop-blur flex items-center gap-2 px-3.5">
                      <i className="ri-map-pin-2-fill text-[17px] 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-11 h-11 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-[18px] leading-none`} />
                    </button>
                  </div>
                </>
              ) : (
                <button
                  type="button"
                  onClick={useCurrentLocation}
                  className="w-full h-full flex flex-col items-center justify-center gap-2.5 cursor-pointer transition-colors hover:bg-background-200/60"
                >
                  <div className="w-14 h-14 rounded-full bg-background-200 flex items-center justify-center">
                    <i
                      className={`${
                        locating ? "ri-loader-4-line animate-spin text-[22px]" : "ri-map-pin-2-line text-[26px]"
                      } 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>
        </div>
      </div>

      <div className="sticky bottom-0 z-30 px-5 py-5 border-t border-background-200/70 bg-background-50">
        <Btn full disabled={!valid} onClick={submit}>
          متابعة
        </Btn>
      </div>
    </div>
  );
}