"use client";

import { useState, useRef, useEffect, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { MessageCircle, ArrowLeft, Phone, Sparkles } from "lucide-react";
import Button from "@/components/ui/Button";
import Input from "@/components/ui/Input";
import { useAuthStore } from "@/lib/store/useAuthStore";

const DEMO = process.env.NEXT_PUBLIC_DEMO_MODE === "true";

export default function LoginPage() {
  return (
    <Suspense fallback={<div className="min-h-dvh grid place-items-center text-faint">…</div>}>
      <LoginInner />
    </Suspense>
  );
}

function LoginInner() {
  const router = useRouter();
  const params = useSearchParams();
  const next = params.get("next") || "/inicio";
  const { requestOTP, verifyOTP, demoLogin, loading, user } = useAuthStore();

  const [step, setStep] = useState<"phone" | "otp">("phone");
  const [phone, setPhone] = useState("");
  const [otp, setOtp] = useState(["", "", "", "", "", ""]);
  const [err, setErr] = useState("");
  const [shake, setShake] = useState(false);
  const refs = useRef<(HTMLInputElement | null)[]>([]);

  useEffect(() => {
    if (user) router.replace(next);
  }, [user, router, next]);

  async function sendCode(e?: React.FormEvent) {
    e?.preventDefault();
    setErr("");
    if (phone.replace(/\D/g, "").length < 8) {
      setErr("Ingresá un número de WhatsApp válido");
      return;
    }
    try {
      await requestOTP(phone);
      setStep("otp");
      setTimeout(() => refs.current[0]?.focus(), 120);
    } catch (e) {
      setErr((e as Error).message || "No pudimos enviar el código");
    }
  }

  function onDigit(i: number, v: string) {
    if (!/^\d*$/.test(v)) return;
    const n = [...otp];
    n[i] = v.slice(-1);
    setOtp(n);
    if (v && i < 5) refs.current[i + 1]?.focus();
    if (n.every((d) => d !== "")) verify(n.join(""));
  }

  function onPaste(e: React.ClipboardEvent) {
    const t = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, 6);
    if (t.length === 6) {
      setOtp(t.split(""));
      verify(t);
    }
  }

  async function verify(code: string) {
    setErr("");
    try {
      await verifyOTP(code);
      router.replace(next);
    } catch (e) {
      setErr((e as Error).message || "Código incorrecto");
      setShake(true);
      setOtp(["", "", "", "", "", ""]);
      setTimeout(() => {
        setShake(false);
        refs.current[0]?.focus();
      }, 400);
    }
  }

  return (
    <div className="min-h-dvh grid place-items-center p-5 bg-canvas">
      <div className="w-full max-w-sm">
        <div className="flex items-center justify-center mb-8">
          <img
            src="/logo-fibromuebles.png"
            alt="Fibromuebles"
            className="h-11 w-auto max-w-full"
          />
        </div>

        <div className="card p-6 shadow-[var(--shadow)]">
          {DEMO ? (
            <div className="text-center">
              <div className="mx-auto mb-4 grid h-14 w-14 place-items-center rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500 text-white">
                <Sparkles size={26} />
              </div>
              <h1 className="text-xl font-extrabold text-ink">ERP de muestra — Bah-IA</h1>
              <p className="text-sm text-ink-soft mt-1 mb-5">
                Entrá con datos de ejemplo y recorré el sistema. Es una demostración: los datos son ficticios.
              </p>
              <Button
                type="button"
                fullWidth
                size="lg"
                loading={loading}
                onClick={async () => {
                  setErr("");
                  try {
                    await demoLogin();
                    router.replace(next);
                  } catch (e) {
                    setErr((e as Error).message || "No se pudo entrar a la demo");
                  }
                }}
              >
                <Sparkles size={18} /> Entrar a la demo
              </Button>
              {err && <p className="text-sm text-bad mt-3 font-medium">{err}</p>}
              <p className="text-xs text-center text-faint mt-4">
                Un producto de Bah-IA · software a medida.
              </p>
            </div>
          ) : (
          <AnimatePresence mode="wait">
            {step === "phone" ? (
              <motion.div
                key="phone"
                initial={{ opacity: 0, x: -16 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -16 }}
              >
                <h1 className="text-xl font-extrabold text-ink">Ingresá con WhatsApp</h1>
                <p className="text-sm text-ink-soft mt-1 mb-5">
                  Te mandamos un código al instante. Tu número es tu cuenta.
                </p>
                <form onSubmit={sendCode} className="flex flex-col gap-4">
                  <Input
                    label="Tu número de WhatsApp"
                    type="tel"
                    inputMode="tel"
                    placeholder="291 412-3456"
                    prefix={<Phone size={16} />}
                    value={phone}
                    onChange={(e) => {
                      setPhone(e.target.value);
                      setErr("");
                    }}
                    error={err}
                    autoFocus
                  />
                  <Button type="submit" fullWidth size="lg" loading={loading}>
                    <MessageCircle size={18} /> Recibir código
                  </Button>
                </form>
                <p className="text-xs text-center text-faint mt-4">
                  Solo personal autorizado. Si no tenés cuenta, pediselá al admin.
                </p>
              </motion.div>
            ) : (
              <motion.div
                key="otp"
                initial={{ opacity: 0, x: 16 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: 16 }}
              >
                <button
                  onClick={() => {
                    setStep("phone");
                    setOtp(["", "", "", "", "", ""]);
                    setErr("");
                  }}
                  className="flex items-center gap-1.5 text-sm text-ink-soft mb-4 hover:text-ink"
                >
                  <ArrowLeft size={16} /> Cambiar número
                </button>
                <h1 className="text-xl font-extrabold text-ink">Ingresá el código</h1>
                <p className="text-sm text-ink-soft mt-1 mb-5">
                  Lo enviamos por WhatsApp a tu número.
                </p>
                <motion.div
                  className="flex gap-2 justify-center"
                  animate={shake ? { x: [0, -9, 9, -7, 7, 0] } : {}}
                  transition={{ duration: 0.4 }}
                  onPaste={onPaste}
                >
                  {otp.map((d, i) => (
                    <input
                      key={i}
                      ref={(el) => {
                        refs.current[i] = el;
                      }}
                      inputMode="numeric"
                      maxLength={1}
                      value={d}
                      onChange={(e) => onDigit(i, e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === "Backspace" && !otp[i] && i > 0)
                          refs.current[i - 1]?.focus();
                      }}
                      className="w-12 h-14 text-center text-xl font-bold rounded-xl bg-canvas border border-line text-ink focus:border-brand focus:outline-none transition-colors"
                    />
                  ))}
                </motion.div>
                {err && (
                  <p className="text-sm text-center text-bad mt-3 font-medium">{err}</p>
                )}
                <button
                  onClick={() => sendCode()}
                  disabled={loading}
                  className="text-sm text-center w-full mt-5 text-ink-soft hover:text-ink"
                >
                  ¿No te llegó? <span className="text-brand font-semibold">Reenviar</span>
                </button>
              </motion.div>
            )}
          </AnimatePresence>
          )}
        </div>
      </div>
    </div>
  );
}
