import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { authRequest, authVerify } from "@/api/driver";
import { digitsOnly, formatPhone } from "@/lib/format";
import { useAuth } from "@/store/auth";
import { Spinner } from "@/components/Spinner";

export function LoginPage() {
  const nav = useNavigate();
  const setSession = useAuth((s) => s.setSession);
  const [phone, setPhone] = useState("");          // national 10 digits
  const [code, setCode] = useState("");
  const [step, setStep] = useState<"phone" | "code">("phone");
  const [channel, setChannel] = useState<string>("");
  const [busy, setBusy] = useState(false);
  const e164 = "7" + phone;

  async function requestCode() {
    if (phone.length < 10) return;
    setBusy(true);
    try {
      const r = await authRequest(e164);
      if (r.status === "onboarding") {
        sessionStorage.setItem("pp-onboarding", JSON.stringify({ ...r.deep_links, phone }));
        nav("/onboarding");
        return;
      }
      setChannel(r.channel);
      setStep("code");
    } catch (err: any) {
      toast.error(err?.response?.status === 404 ? "Номер не найден. Обратитесь в парк." : "Не удалось отправить код");
    } finally {
      setBusy(false);
    }
  }

  async function verify() {
    if (code.length < 4) return;
    setBusy(true);
    try {
      const r = await authVerify(e164, code);
      setSession(r.token, r.driver_id);
      nav("/");
    } catch {
      toast.error("Неверный или просроченный код");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="pt-16">
      <h1 className="text-xl font-extrabold mb-1">Премиум Водитель</h1>
      <p className="text-muted text-sm mb-8">Вход в приложение</p>

      {step === "phone" ? (
        <>
          <input
            inputMode="numeric"
            placeholder="Номер телефона"
            value={phone ? formatPhone(phone) : ""}
            onChange={(e) => setPhone(digitsOnly(e.target.value).replace(/^7/, "").slice(0, 10))}
            className="card w-full px-4 py-3 mb-3 text-base bg-white"
          />
          <button className="btn-primary" disabled={busy || phone.length < 10} onClick={requestCode}>
            {busy ? <Spinner /> : "Получить код"}
          </button>
          <p className="text-muted text-xs mt-3">Код придёт в Telegram или MAX.</p>
        </>
      ) : (
        <>
          <p className="text-sm mb-2">Код отправлен в {channel === "max" ? "MAX" : "Telegram"}.</p>
          <input
            inputMode="numeric"
            placeholder="Код из сообщения"
            value={code}
            onChange={(e) => setCode(digitsOnly(e.target.value).slice(0, 6))}
            className="card w-full px-4 py-3 mb-3 text-base tracking-widest bg-white"
          />
          <button className="btn-primary" disabled={busy || code.length < 4} onClick={verify}>
            {busy ? <Spinner /> : "Войти"}
          </button>
          <button className="btn-ghost mt-2" onClick={() => setStep("phone")}>Изменить номер</button>
        </>
      )}
    </div>
  );
}
