"use client";

import React, { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import {
  Lock,
  Mail,
  ArrowRight,
  AlertCircle,
  Eye,
  EyeOff,
  Sparkles,
  ShieldCheck
} from "lucide-react";
import { useAppStore } from "@/lib/store";
import { SquaresTerminal } from "@/components/ui/SquaresTerminal";
import { ThemeToggle } from "@/components/ui/ThemeToggle";

export default function LoginPage() {
  const router = useRouter();
  const { login, siteSettings } = useAppStore();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [rememberMe, setRememberMe] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState("");

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMsg("");

    if (!email.trim() || !password.trim()) {
      setErrorMsg("Please enter your business email and password.");
      return;
    }

    setIsLoading(true);

    setTimeout(() => {
      const res = login(email.trim(), password.trim());
      setIsLoading(false);

      if (!res.success) {
        setErrorMsg(res.error || "Authentication failed. Please verify your email and password.");
        return;
      }

      if (res.user?.role === "client") {
        router.push("/portal");
      } else {
        router.push("/admin/dashboard");
      }
    }, 450);
  };

  return (
    <div className="min-h-screen flex flex-col lg:flex-row bg-background text-foreground font-sans selection:bg-[#024d37] selection:text-white">
      {/* 1. LEFT COLUMN: HERO SQUARES TERMINAL ANIMATION */}
      <div className="w-full lg:w-1/2 relative min-h-[420px] lg:min-h-screen border-b lg:border-b-0 lg:border-r border-border bg-card/40 flex items-center justify-center p-0 overflow-hidden">
        <SquaresTerminal
          direction="diagonal"
          speed={0.6}
          squareSize={38}
          borderColor="rgba(2, 77, 55, 0.25)"
          hoverFillColor="rgba(2, 77, 55, 0.7)"
          className="h-full min-h-full"
        />
      </div>

      {/* 2. RIGHT COLUMN: SEAMLESS & UNIQUE AUTHENTICATION FORM (NO ENCLOSING BOXED CARD) */}
      <div className="w-full lg:w-1/2 flex flex-col justify-between p-6 sm:p-10 lg:p-16 relative overflow-y-auto">
        {/* Top Header */}


        {/* Center Container: Pure Seamless Form */}
        <div className="max-w-md w-full mx-auto my-8 space-y-8">
          {/* Logo & Headline */}
          <div className="space-y-4 text-left">


            <div className="space-y-2">
              <div className="inline-flex items-center gap-1.5 font-mono text-xs text-[#024d37] font-semibold">
                <span className="h-2 w-2 rounded-full bg-[#024d37] animate-pulse" />
                <span>// CORPORATE AUTHENTICATION</span>
              </div>
              <h1 className="text-3xl sm:text-4xl font-bold tracking-tight text-foreground">
                Sign In to Your Workspace
              </h1>
              <p className="text-xs sm:text-sm text-muted-foreground leading-relaxed">
                Enter your corporate credentials to access your administration dashboard or client project portal.
              </p>
            </div>
          </div>

          {/* Form Area - Clean, Borderless & Seamless */}
          <div className="space-y-6">
            {errorMsg && (
              <div className="rounded-2xl border border-destructive/40 bg-destructive/10 p-3.5 text-xs text-destructive flex items-start gap-2.5 animate-in fade-in">
                <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
                <span>{errorMsg}</span>
              </div>
            )}

            <form onSubmit={handleLogin} className="space-y-5 font-sans">
              <div className="space-y-2">
                <label className="font-mono text-xs text-foreground block font-semibold tracking-wide">
                  [BUSINESS EMAIL]
                </label>
                <div className="relative group">
                  <Mail className="absolute left-4 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground group-focus-within:text-[#024d37] transition-colors" />
                  <input
                    type="email"
                    required
                    placeholder="name@company.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full rounded-2xl border border-border bg-card/60 backdrop-blur-sm pl-11 pr-4 py-3.5 text-foreground focus:border-[#024d37] focus:ring-2 focus:ring-[#024d37]/20 focus:outline-none font-sans text-xs transition-all shadow-xs"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <label className="font-mono text-xs text-foreground block font-semibold tracking-wide">
                    [PASSWORD]
                  </label>
                  <span className="font-mono text-[11px] text-[#024d37] hover:underline cursor-pointer">
                    Forgot Password?
                  </span>
                </div>
                <div className="relative group">
                  <Lock className="absolute left-4 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground group-focus-within:text-[#024d37] transition-colors" />
                  <input
                    type={showPassword ? "text" : "password"}
                    required
                    placeholder="Enter your corporate password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full rounded-2xl border border-border bg-card/60 backdrop-blur-sm pl-11 pr-11 py-3.5 text-foreground focus:border-[#024d37] focus:ring-2 focus:ring-[#024d37]/20 focus:outline-none font-sans text-xs transition-all shadow-xs"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground cursor-pointer"
                    aria-label={showPassword ? "Hide password" : "Show password"}
                  >
                    {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
              </div>

              <div className="flex items-center justify-between font-mono text-xs pt-1">
                <label className="flex items-center gap-2.5 text-muted-foreground cursor-pointer select-none">
                  <input
                    type="checkbox"
                    checked={rememberMe}
                    onChange={(e) => setRememberMe(e.target.checked)}
                    className="rounded border-border text-[#024d37] focus:ring-[#024d37] h-4 w-4 cursor-pointer"
                  />
                  <span>Keep session active</span>
                </label>
              </div>

              <button
                type="submit"
                disabled={isLoading}
                className="w-full inline-flex items-center justify-center gap-2 rounded-full bg-[#024d37] py-4 font-mono text-xs font-bold uppercase tracking-[0.14em] text-white hover:bg-[#036549] transition-all shadow-xl shadow-[#024d37]/25 active:scale-[0.99] cursor-pointer disabled:opacity-70 mt-2"
              >
                {isLoading ? (
                  <span className="flex items-center gap-2">
                    <span className="h-4 w-4 rounded-full border-2 border-white border-t-transparent animate-spin" />
                    Authenticating Session...
                  </span>
                ) : (
                  <span>Sign In to Workspace →</span>
                )}
              </button>
            </form>

            {/* Bottom Onboarding Link */}
            <div className="pt-6 border-t border-border font-mono text-xs text-center space-y-2">
              <div className="text-muted-foreground">
                New Enterprise Client?{" "}
                <Link href="/register" className="text-[#024d37] font-bold hover:underline">
                  Create Organization Account →
                </Link>
              </div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="text-center font-mono text-[11px] text-muted-foreground">
          © {new Date().getFullYear()} {siteSettings?.company_name || "AetherSoft Innovations"}. Beyond The Limits.
        </div>
      </div>
    </div>
  );
}
