// Path: src/app/(auth)/login/LoginForm.tsx
"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { useAdminStore } from "@/store/adminStore";

// ─── Icons ────────────────────────────────────────────────────────────────────

function EyeIcon({ show }: { show: boolean }) {
  return show ? (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94" />
      <path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19" />
      <line x1="1" y1="1" x2="23" y2="23" />
    </svg>
  ) : (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  );
}

function Spinner() {
  return (
    <svg className="animate-spin" width="18" height="18" viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="12" r="10" stroke="white" strokeWidth="3" strokeOpacity="0.3" />
      <path d="M12 2a10 10 0 0 1 10 10" stroke="white" strokeWidth="3" strokeLinecap="round" />
    </svg>
  );
}

// ─── Types ────────────────────────────────────────────────────────────────────

type Step = "credentials" | "twofa";

// ─── Component ────────────────────────────────────────────────────────────────

export default function LoginForm() {
  const router     = useRouter();
  const { setUser } = useAdminStore();

  // Step state
  const [step, setStep]             = useState<Step>("credentials");
  const [employeeId, setEmployeeId] = useState("");

  // Credentials step
  const [email, setEmail]       = useState("");
  const [password, setPassword] = useState("");
  const [showPass, setShowPass] = useState(false);

  // 2FA step — 6 separate digit inputs
  const [digits, setDigits] = useState<string[]>(["", "", "", "", "", ""]);

  // Shared
  const [error, setError]     = useState("");
  const [loading, setLoading] = useState(false);
  const [resendMsg, setResendMsg] = useState("");

  // ─── Step 1: Credentials submit ───────────────────────────────────────────

  async function handleCredentials(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setLoading(true);

    try {
      const res  = await fetch("/api/auth/login", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({ email, password }),
      });
      const data = await res.json();

      if (!res.ok || !data.success) {
        setError(data.message ?? "Login failed");
        return;
      }

      // 2FA required — move to second step
      if (data.twoFa) {
        setEmployeeId(data.employeeId);
        setStep("twofa");
        return;
      }

      // No 2FA — login complete
      finalizeLogin(data);

    } catch {
      setError("Network error — please try again");
    } finally {
      setLoading(false);
    }
  }

  // ─── Step 2: 2FA code submit ───────────────────────────────────────────────

  async function handle2FA(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setLoading(true);

    const code = digits.join("");
    if (code.length < 6) {
      setError("Please enter the complete 6-digit code");
      setLoading(false);
      return;
    }

    try {
      const res  = await fetch("/api/auth/2fa/verify", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({ employeeId, code }),
      });
      const data = await res.json();

      if (!res.ok || !data.success) {
        setError(data.message ?? "Verification failed");
        // Clear digits on wrong code
        setDigits(["", "", "", "", "", ""]);
        document.getElementById("digit-0")?.focus();
        return;
      }

      finalizeLogin(data);

    } catch {
      setError("Network error — please try again");
    } finally {
      setLoading(false);
    }
  }

  // ─── Resend code ───────────────────────────────────────────────────────────

  async function handleResend() {
    setResendMsg("");
    setError("");

    try {
      const res  = await fetch("/api/auth/2fa/resend", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({ employeeId }),
      });
      const data = await res.json();

      if (!res.ok || !data.success) {
        setError(data.message ?? "Failed to resend code");
        return;
      }

      setResendMsg("New code sent to your email");
      setDigits(["", "", "", "", "", ""]);
      document.getElementById("digit-0")?.focus();

    } catch {
      setError("Network error — please try again");
    }
  }

  // ─── Finalize login — store user + redirect ────────────────────────────────

  function finalizeLogin(data: any) {
    const { employee } = data.data;

    setUser({
      id:          employee.id,
      email:       employee.email,
      firstName:   employee.firstName,
      lastName:    employee.lastName,
    });

    setTimeout(() => router.push("/admin/dashboard"), 100);
  }

  // ─── OTP digit input handler ───────────────────────────────────────────────

  function handleDigit(index: number, value: string) {
    // Allow only single digit
    const digit = value.replace(/\D/g, "").slice(-1);
    const next  = [...digits];
    next[index] = digit;
    setDigits(next);

    // Auto-focus next
    if (digit && index < 5) {
      document.getElementById(`digit-${index + 1}`)?.focus();
    }
  }

  function handleDigitKeyDown(index: number, e: React.KeyboardEvent) {
    if (e.key === "Backspace" && !digits[index] && index > 0) {
      document.getElementById(`digit-${index - 1}`)?.focus();
    }
  }

  function handleDigitPaste(e: React.ClipboardEvent) {
    e.preventDefault();
    const pasted = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, 6);
    const next   = [...digits];
    pasted.split("").forEach((ch, i) => { next[i] = ch; });
    setDigits(next);
    document.getElementById(`digit-${Math.min(pasted.length, 5)}`)?.focus();
  }

  // ─── Shared styles ─────────────────────────────────────────────────────────

  const inputStyle = {
    background: "var(--color-surface-alt)",
    border:     "1.5px solid var(--color-border)",
    color:      "var(--color-text)",
  } as React.CSSProperties;

  const focusStyle = { borderColor: "var(--color-cta)", boxShadow: "0 0 0 3px rgba(217,119,6,0.12)" };
  const blurStyle  = { borderColor: "var(--color-border)", boxShadow: "none" };

  // ─── Render ────────────────────────────────────────────────────────────────

  return (
    <AnimatePresence mode="wait">

      {/* ── Step 1: Credentials ── */}
      {step === "credentials" && (
        <motion.form
          key="credentials"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -20 }}
          transition={{ duration: 0.3 }}
          onSubmit={handleCredentials}
          className="flex flex-col gap-5"
        >
          {/* Email */}
          <div className="flex flex-col gap-1.5">
            <label htmlFor="email" className="text-sm font-medium" style={{ color: "var(--color-text-secondary)" }}>
              Work Email
            </label>
            <motion.div whileHover={{ scale: 1.01 }} whileTap={{ scale: 0.99 }}>
              <input
                id="email" type="email" required autoComplete="email"
                value={email} onChange={(e) => setEmail(e.target.value)}
                placeholder="you@company.com"
                className="w-full px-4 py-3 rounded-xl text-sm outline-none transition-all duration-200"
                style={inputStyle}
                onFocus={(e) => Object.assign(e.currentTarget.style, focusStyle)}
                onBlur={(e)  => Object.assign(e.currentTarget.style, blurStyle)}
              />
            </motion.div>
          </div>

          {/* Password */}
          <div className="flex flex-col gap-1.5">
            <div className="flex items-center justify-between">
              <label htmlFor="password" className="text-sm font-medium" style={{ color: "var(--color-text-secondary)" }}>
                Password
              </label>
              <a href="/forgot-password" className="text-xs font-medium hover:opacity-80" style={{ color: "var(--color-cta)" }}>
                Forgot password?
              </a>
            </div>
            <div className="relative">
              <motion.div whileHover={{ scale: 1.01 }} whileTap={{ scale: 0.99 }}>
                <input
                  id="password" type={showPass ? "text" : "password"} required
                  autoComplete="current-password" value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="••••••••"
                  className="w-full px-4 py-3 pr-12 rounded-xl text-sm outline-none transition-all duration-200"
                  style={inputStyle}
                  onFocus={(e) => Object.assign(e.currentTarget.style, focusStyle)}
                  onBlur={(e)  => Object.assign(e.currentTarget.style, blurStyle)}
                />
              </motion.div>
              <button
                type="button" onClick={() => setShowPass((v) => !v)}
                className="absolute right-3 top-1/2 -translate-y-1/2 p-1 rounded-lg hover:opacity-80"
                style={{ color: "var(--color-text-muted)" }}
                aria-label={showPass ? "Hide password" : "Show password"}
              >
                <EyeIcon show={showPass} />
              </button>
            </div>
          </div>

          <ErrorBox error={error} />

          <SubmitButton loading={loading} label="Sign In" />
        </motion.form>
      )}

      {/* ── Step 2: 2FA code ── */}
      {step === "twofa" && (
        <motion.form
          key="twofa"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -20 }}
          transition={{ duration: 0.3 }}
          onSubmit={handle2FA}
          className="flex flex-col gap-5"
        >
          {/* Header */}
          <div className="text-center">
            <p className="text-sm" style={{ color: "var(--color-text-secondary)" }}>
              A 6-digit verification code has been sent to your email. Enter it below.
            </p>
          </div>

          {/* 6-digit OTP inputs */}
          <div className="flex justify-center gap-2">
            {digits.map((digit, i) => (
              <input
                key={i}
                id={`digit-${i}`}
                type="text"
                inputMode="numeric"
                maxLength={1}
                value={digit}
                onChange={(e) => handleDigit(i, e.target.value)}
                onKeyDown={(e) => handleDigitKeyDown(i, e)}
                onPaste={i === 0 ? handleDigitPaste : undefined}
                className="w-11 h-14 text-center text-xl font-bold rounded-xl outline-none transition-all duration-200"
                style={{
                  background:   "var(--color-surface-alt)",
                  border:       `2px solid ${digit ? "var(--color-cta)" : "var(--color-border)"}`,
                  color:        "var(--color-text)",
                }}
                onFocus={(e) => Object.assign(e.currentTarget.style, { borderColor: "var(--color-cta)", boxShadow: "0 0 0 3px rgba(217,119,6,0.12)" })}
                onBlur={(e)  => Object.assign(e.currentTarget.style, { borderColor: digit ? "var(--color-cta)" : "var(--color-border)", boxShadow: "none" })}
              />
            ))}
          </div>

          <ErrorBox error={error} />

          {/* Resend */}
          <div className="text-center">
            {resendMsg ? (
              <p className="text-xs" style={{ color: "var(--color-success)" }}>{resendMsg}</p>
            ) : (
              <button
                type="button" onClick={handleResend}
                className="text-xs font-medium hover:opacity-80 transition-opacity"
                style={{ color: "var(--color-cta)" }}
              >
                Didn`t receive the code? Resend
              </button>
            )}
          </div>

          <SubmitButton loading={loading} label="Verify" />

          {/* Back to login */}
          <button
            type="button"
            onClick={() => { setStep("credentials"); setError(""); setDigits(["","","","","",""]); }}
            className="text-xs text-center hover:opacity-80 transition-opacity"
            style={{ color: "var(--color-text-muted)" }}
          >
            ← Back to login
          </button>
        </motion.form>
      )}

    </AnimatePresence>
  );
}

// ─── Shared sub-components ────────────────────────────────────────────────────

function ErrorBox({ error }: { error: string }) {
  return (
    <AnimatePresence>
      {error && (
        <motion.div
          initial={{ opacity: 0, y: -10, height: 0 }}
          animate={{ opacity: 1, y: 0, height: "auto" }}
          exit={{ opacity: 0, y: -10, height: 0 }}
          className="overflow-hidden"
        >
          <div
            className="flex items-center gap-2.5 px-4 py-3 rounded-xl text-sm"
            style={{ background: "rgba(239,68,68,0.1)", color: "var(--color-danger)", border: "1px solid rgba(239,68,68,0.2)" }}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="shrink-0">
              <circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
            </svg>
            <span>{error}</span>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}

function SubmitButton({ loading, label }: { loading: boolean; label: string }) {
  return (
    <motion.button
      type="submit" disabled={loading}
      whileHover={{ scale: loading ? 1 : 1.02 }}
      whileTap={{ scale: loading ? 1 : 0.98 }}
      className="relative w-full overflow-hidden group mt-1"
    >
      <div
        className="absolute inset-0 transition-transform duration-300 group-hover:scale-x-105"
        style={{ background: "linear-gradient(90deg, var(--color-cta), var(--color-cta-hover))", opacity: loading ? 0.7 : 1 }}
      />
      <div className="relative flex items-center justify-center gap-2 py-3.5 rounded-2xl text-sm font-semibold text-white">
        {loading ? (
          <><Spinner /><span>Please wait...</span></>
        ) : (
          <>
            <span>{label}</span>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="group-hover:translate-x-1 transition-transform">
              <line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" />
            </svg>
          </>
        )}
      </div>
    </motion.button>
  );
}