"use client";

import { Suspense, useState } from "react";
import { signIn, getSession } from "next-auth/react";
import { useRouter, useSearchParams } from "next/navigation";
import { motion, useReducedMotion } from "motion/react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Lock, Mail, Eye, EyeOff } from "lucide-react";
import { AppSpinner } from "@/components/ui/app-loader";
import { ThemeToggle } from "@/components/layout/theme-toggle";
import { LoginPerformanceScene } from "@/components/auth/login-performance-scene";
import { BrandLockup } from "@/components/brand/brand-logo";
import { easeOutExpo, staggerContainer, staggerItem } from "@/lib/motion";

function BrandMark() {
  return (
    <BrandLockup onDarkSurface height={42} priority />
  );
}

function LoginForm() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [rememberMe, setRememberMe] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const reduceMotion = useReducedMotion();

  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get("callbackUrl") || "/dashboard";
  const sessionExpired = searchParams.get("expired") === "1";

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError("");

    try {
      const result = await signIn("credentials", {
        email,
        password,
        remember: rememberMe ? "true" : "false",
        redirect: false,
      });

      if (result?.error) {
        setError("Invalid email or password");
      } else if (result?.ok) {
        const session = await getSession();
        if (session?.user) {
          const roleRedirects = {
            SUPER_ADMIN: "/dashboard/admin",
            UPPER_MANAGEMENT: "/dashboard/management",
            MANAGER: "/dashboard/manager",
            UNIT_LEAD: "/dashboard/lead",
            MEMBER: "/dashboard/member",
          };

          const redirectUrl =
            roleRedirects[session.user.role as keyof typeof roleRedirects] ||
            "/dashboard";
          router.push(redirectUrl);
        } else {
          router.push(callbackUrl);
        }
      }
    } catch {
      setError("An unexpected error occurred");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen grid lg:grid-cols-2 bg-background">
      {/* Full-bleed scene; brand top, copy anchored at bottom */}
      <div className="relative hidden lg:flex min-h-screen overflow-hidden">
        <LoginPerformanceScene />

        <div className="relative z-10 flex flex-1 flex-col justify-between p-12 pointer-events-none">
          <motion.div
            initial={reduceMotion ? false : { opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.45, ease: easeOutExpo }}
          >
            <BrandMark />
          </motion.div>

          <div className="space-y-8">
            <motion.div
              className="max-w-md space-y-4"
              initial={reduceMotion ? false : { opacity: 0, y: 18 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.15, duration: 0.55, ease: easeOutExpo }}
            >
              <p className="text-xs font-medium uppercase tracking-[0.18em] text-white/80">
                Employee performance &amp; KPIs
              </p>
              <h1 className="text-4xl font-semibold tracking-tight leading-[1.15] text-white">
                Clarity for every evaluation.
              </h1>
              <p className="text-sm text-white/80 leading-relaxed max-w-sm">
                Track KPIs, review goals, and manage team performance — a
                focused workspace for software organisations that measure what
                matters.
              </p>
            </motion.div>

            <motion.p
              className="text-xs text-white/60"
              initial={reduceMotion ? false : { opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.4, duration: 0.4 }}
            >
              Authorized personnel only
            </motion.p>
          </div>
        </div>
      </div>

      {/* Form panel */}
      <div className="relative flex flex-col justify-center px-6 py-12 sm:px-12">
        <div className="absolute top-4 right-4">
          <ThemeToggle />
        </div>

        <motion.div
          className="mx-auto w-full max-w-sm space-y-8"
          variants={staggerContainer}
          initial="initial"
          animate="animate"
        >
          <motion.div variants={staggerItem} className="space-y-2 lg:hidden">
            <div className="mb-8">
              <BrandLockup height={36} priority />
            </div>
          </motion.div>

          <motion.div variants={staggerItem} className="space-y-2">
            <h2 className="text-2xl font-semibold tracking-tight">Sign in</h2>
            <p className="text-sm text-muted-foreground">
              Enter your work credentials to continue
            </p>
          </motion.div>

          <motion.form
            variants={staggerItem}
            onSubmit={handleSubmit}
            className="space-y-4"
          >
            {sessionExpired && !error && (
              <Alert variant="destructive">
                <AlertDescription>
                  Your session has expired. Please sign in again.
                </AlertDescription>
              </Alert>
            )}

            {error && (
              <Alert variant="destructive">
                <AlertDescription>{error}</AlertDescription>
              </Alert>
            )}

            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  id="email"
                  type="email"
                  placeholder="name@company.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="pl-10 h-11 bg-card"
                  required
                  disabled={isLoading}
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="password">Password</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  placeholder="Enter your password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="pl-10 pr-10 h-11 bg-card"
                  required
                  disabled={isLoading}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                  disabled={isLoading}
                  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 gap-2">
              <Checkbox
                id="remember"
                checked={rememberMe}
                onCheckedChange={(checked) => setRememberMe(checked === true)}
                disabled={isLoading}
              />
              <Label
                htmlFor="remember"
                className="text-sm font-normal text-muted-foreground cursor-pointer leading-none"
              >
                Remember me for 30 days
              </Label>
            </div>

            <Button type="submit" className="w-full h-11" disabled={isLoading}>
              {isLoading ? (
                <>
                  <AppSpinner className="mr-2" />
                  Signing in...
                </>
              ) : (
                "Continue"
              )}
            </Button>
          </motion.form>

          <motion.p
            variants={staggerItem}
            className="text-center text-sm text-muted-foreground"
          >
            Need an account? Contact your administrator.
          </motion.p>
        </motion.div>
      </div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={null}>
      <LoginForm />
    </Suspense>
  );
}
