"use client";

import { useRouter } from "next/navigation";
import { SinghLogo } from "@/components/singh-logo";
import { useState, useRef, useEffect } from "react";
import { Mail, Hash, CheckCircle } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { useLogin } from "../hooks/use-login";
import { consumeIntendedPath } from "@/lib/auth-redirect";
export function LoginForm() {
  const router = useRouter();
  const emailRef = useRef<HTMLInputElement>(null);
  const [email, setEmail] = useState("");
  const [otp, setOtp] = useState("");
  const [fieldErrors, setFieldErrors] = useState<{
    email?: string;
    otp?: string;
  }>({});

  const {
    data,
    loading,
    error,
    sendOtp,
    verifyOtp,
    resetOtp,
    otpSent,
    clearError,
  } = useLogin();

  // Redirect on successful login
  useEffect(() => {
    if (data) {
      router.replace(consumeIntendedPath(window.location.search));
    }
  }, [data, router]);

  // --- Send OTP ---
  const handleSendOtp = async (): Promise<void> => {
    // Read directly from the DOM to handle browser autofill
    const domEmail = emailRef.current?.value ?? email;
    if (domEmail !== email) {
      setEmail(domEmail);
    }
    if (!domEmail.trim()) {
      setFieldErrors((prev) => ({ ...prev, email: "Email is required" }));
      return;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(domEmail.trim())) {
      setFieldErrors((prev) => ({
        ...prev,
        email: "Please enter a valid email address",
      }));
      return;
    }
    setFieldErrors((prev) => ({ ...prev, email: undefined }));

    await sendOtp({ email: domEmail.trim() });
  };

  // --- Verify OTP ---
  const handleVerifyOtp = async (e: React.FormEvent): Promise<void> => {
    e.preventDefault();
    if (!validateOtp()) return;

    // H4: Hook catches errors → toast.error + setError. No re-throw.
    await verifyOtp({ email: email.trim(), otp });
  };

  // --- Validate OTP ---
  const validateOtp = (): boolean => {
    const errors: { email?: string; otp?: string } = {};

    if (!email.trim()) {
      errors.email = "Email is required";
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
      errors.email = "Please enter a valid email address";
    }

    if (!otp.trim()) {
      errors.otp = "Code is required";
    } else if (!/^\d{6}$/.test(otp.trim())) {
      errors.otp = "Please enter a valid 6-digit Code";
    }

    setFieldErrors(errors);
    return Object.keys(errors).length === 0;
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-navy-950 p-4 sm:p-6 lg:p-8">
      {/* Main Card Container */}
      <div className="flex w-full max-w-5xl overflow-hidden rounded-2xl bg-white shadow-2xl lg:max-w-[1100px] lg:min-h-[620px]">
        {/* ============================================ */}
        {/* Left Panel - Branding with Background Image */}
        {/* ============================================ */}
        <div className="hidden w-[48%] relative lg:flex flex-col justify-between">
          {/* Background Image with Overlay */}
          <div
            className="absolute inset-0 bg-cover bg-center"
            style={{
              backgroundImage: `url('https://images.unsplash.com/photo-1562774053-701939374585?w=1200&q=80')`,
            }}
          />
          {/* Dark Overlay */}
          <div className="absolute inset-0 bg-gradient-to-b from-navy-950/80 via-navy-900/70 to-navy-950/90" />

          {/* Content */}
          <div className="relative z-10 flex flex-col justify-between h-full p-10">
            {/* Top: SINGH Logo */}
            <div>
              <SinghLogo className="w-40" />
            </div>

            {/* Middle: Welcome Text */}
            <div className="mt-auto mb-8">
              <p className="mb-2 text-xs font-semibold uppercase tracking-[0.2em] text-white/70">
                Admin Portal
              </p>
              <h1 className="text-4xl font-bold leading-tight text-white">
                Welcome to<br />Singh Order Management. 
              </h1>
              <div className="mt-4 mb-5 h-[2px] w-12 bg-white/50" />
              <p className="max-w-sm text-sm leading-relaxed text-white/70">
                Sign in to place orders, track deliveries, and manage your community&apos;s print supplies.
              </p>
            </div>
          </div>
        </div>

        {/* ============================================ */}
        {/* Right Panel - Login Form (White) */}
        {/* ============================================ */}
        <div className="flex w-full items-center justify-center p-8 sm:p-10 lg:w-[52%] bg-white">
          <div className="w-full max-w-md">
            {/* Mobile Logo */}
            <div className="mb-8 text-center lg:hidden">
              <SinghLogo className="mx-auto mb-1 w-32" />
              <p className="text-xs font-semibold uppercase tracking-[0.15em] text-navy-400">
                Admin Portal
              </p>
            </div>

            {/* Welcome Text */}
            <div className="mb-8">
              {/* <p className="mb-1 text-[11px] font-semibold uppercase tracking-[0.2em] text-navy-400">
                Secure Access
              </p> */}
              <h2 className="text-2xl font-bold text-navy-950">
                Log in to your account
              </h2>
              <p className="mt-1.5 text-sm text-gray-500">
                Enter your work email and we&apos;ll send you a verification code.
              </p>
            </div>

            {/* Server Error */}
            {error && (
              <div className="mb-6 rounded-lg border border-red-200 bg-red-50 p-4">
                <p className="text-sm text-red-600">{error}</p>
              </div>
            )}

            {/* ============================================ */}
            {/* STEP 1: Email (when no CODE sent) */}
            {/* ============================================ */}
            {!otpSent && (
              <div className="space-y-5">
                  <div className="space-y-4">
                    {/* Email Input */}
                    <div>
                      <label className="mb-1.5 block text-sm font-medium text-gray-700">
                        Email address
                      </label>
                      <Input
                        ref={emailRef}
                        type="email"
                        placeholder=" name@company.com"
                        autoComplete="off"
                        icon={<Mail className="h-4 w-4 text-gray-400" />}
                        error={fieldErrors.email}
                        disabled={loading}
                        value={email}
                        onChange={(e) => {
                          setEmail(e.target.value);
                          if (fieldErrors.email) {
                            setFieldErrors((prev) => ({ ...prev, email: undefined }));
                          }
                          if (error) clearError();
                        }}
                        onKeyDown={(e) => {
                          if (e.key === "Enter") {
                            e.preventDefault();
                            handleSendOtp();
                          }
                        }}
                      />
                    </div>

                    <Button
                      type="button"
                      className="w-full rounded-lg bg-navy-900 text-white hover:bg-navy-800 font-semibold tracking-wide"
                      size="lg"
                      onClick={handleSendOtp}
                      loading={loading}
                      disabled={loading}
                    >
                      Send Code
                    </Button>
                  </div>
              </div>
            )}

            {/* ============================================ */}
            {/* STEP 2: OTP Verification */}
            {/* ============================================ */}
            {otpSent && (
              <form onSubmit={handleVerifyOtp} className="space-y-5">
                {/* Success banner */}
                <div className="flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 p-3">
                  <CheckCircle className="h-4 w-4 flex-shrink-0 text-green-600" />
                  <p className="text-sm text-green-700">
                    Code sent to{" "}
                    <span className="font-medium text-green-800">{email}</span>
                  </p>
                </div>

                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">
                    Email address
                  </label>
                  <Input
                    type="email"
                    placeholder="Enter Email"
                    icon={<Mail className="h-4 w-4 text-gray-400" />}
                    error={fieldErrors.email}
                    disabled
                    value={email}
                    onChange={() => {}}
                  />
                </div>

                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">
                    Enter Code
                  </label>
                  <Input
                    type="text"
                    placeholder="Enter 6-digit Code"
                    icon={<Hash className="h-4 w-4 text-gray-400" />}
                    error={fieldErrors.otp}
                    disabled={loading}
                    value={otp}
                    onChange={(e) => {
                      const val = e.target.value
                        .replace(/\D/g, "")
                        .slice(0, 6);
                      setOtp(val);
                      if (fieldErrors.otp) {
                        setFieldErrors((prev) => ({ ...prev, otp: undefined }));
                      }
                      if (error) clearError();
                    }}
                    maxLength={6}
                    autoFocus
                  />
                </div>

                <div className="flex items-center justify-between">
                  <p className="text-xs text-gray-400">
                    Check your email for the code
                  </p>
                  <button
                    type="button"
                    onClick={() => {
                      setOtp("");
                      handleSendOtp();
                    }}
                    className="text-xs font-medium text-navy-600 hover:text-navy-800 transition-colors"
                    disabled={loading}
                  >
                    Resend Code
                  </button>
                </div>

                <Button
                  type="submit"
                  className="w-full rounded-lg bg-navy-900 text-white hover:bg-navy-800 font-semibold tracking-wide"
                  size="lg"
                  loading={loading}
                  disabled={loading}
                >
                  {loading ? "Verifying..." : "VERIFY & SIGN IN"}
                </Button>

                <button
                  type="button"
                  onClick={() => {
                    resetOtp();
                    setOtp("");
                  }}
                  className="w-full text-center text-sm text-gray-400 hover:text-gray-600 transition-colors"
                >
                  ← Change email
                </button>
              </form>
            )}


            {/* Footer */}
            <div className="mt-8 text-center">
              <p className="text-xs text-gray-400">
                © {new Date().getFullYear()} Singh Order Management. All rights
                reserved.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
