"use client";

import { useState } from "react";
import { useLogin } from "@/modules/auth/hooks/auth.hooks";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { ShieldCheck, Key, Mail, Eye, EyeOff } from "lucide-react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useAppDispatch } from "@/lib/store";
import { setCurrentUser } from "@/modules/auth/slices/authSlice";

type FieldErrors = { email?: string; password?: string };

function FieldError({ msg }: { msg?: string }) {
  if (!msg) return null;
  return <p className="text-xs text-destructive mt-1">{msg}</p>;
}

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
  const { mutate: login, isPending } = useLogin();
  const router = useRouter();
  const dispatch = useAppDispatch();

  function validate(): FieldErrors {
    const errs: FieldErrors = {};
    if (!email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
      errs.email = "Enter a valid email address";
    if (!password)
      errs.password = "Password is required";
    else if (password.length < 8)
      errs.password = "Password must be at least 8 characters";
    return errs;
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length > 0) {
      setFieldErrors(errs);
      return;
    }
    setFieldErrors({});
    login(
      { email: email.trim(), password },
      {
        onSuccess: ({ user }) => {
          const roleRedirect: Record<string, string> = {
            SUPERADMIN: "/superadmin/dashboard",
            ADMIN: "/admin/dashboard",
            MANAGER: "/manager/dashboard",
            EMPLOYEE: "/employee/dashboard",
            CLIENT: "/client/dashboard",
          };
          const dest = roleRedirect[user?.role] ?? "/client/dashboard";
          dispatch(setCurrentUser(user));
          router.replace(dest);
        },
        onError: (error: any) => {
          const msg = error?.response?.data?.error || error?.response?.data?.message || "Login failed. Please try again.";
          if (msg.toLowerCase().includes("no account") || msg.toLowerCase().includes("email")) {
            setFieldErrors({ email: msg });
          } else if (msg.toLowerCase().includes("incorrect password")) {
            setFieldErrors({ password: msg });
          } else if (msg.toLowerCase().includes("inactive") || msg.toLowerCase().includes("verified") || msg.toLowerCase().includes("suspended")) {
            setFieldErrors({ email: msg });
          } else {
            setFieldErrors({ password: msg });
          }
        },
      }
    );
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-background p-4 relative overflow-hidden">
      <div className="absolute inset-0 bg-[linear-gradient(to_right,#80808012_1px,transparent_1px),linear-gradient(to_bottom,#80808012_1px,transparent_1px)] bg-[size:24px_24px] pointer-events-none" />

      <Card className="w-full max-w-md border-border bg-card shadow-xl relative overflow-hidden">
        <CardHeader className="space-y-1 text-center relative">
          <div className="mx-auto bg-primary/10 w-12 h-12 rounded-2xl flex items-center justify-center mb-2 border border-primary/20">
            <ShieldCheck className="h-6 w-6 text-primary" />
          </div>
          <CardTitle className="text-2xl font-bold tracking-tight text-card-foreground">
            Welcome back to TaxFend
          </CardTitle>
          <CardDescription className="text-muted-foreground">
            Sign in to access your account
          </CardDescription>
        </CardHeader>

        <CardContent className="space-y-4 relative">
          <form onSubmit={handleSubmit} className="space-y-4" noValidate>
            {/* Email */}
            <div className="space-y-1">
              <Label htmlFor="email" className="text-foreground flex items-center gap-2">
                <Mail className="h-4 w-4 text-primary" /> Email Address
              </Label>
              <Input
                id="email"
                type="email"
                placeholder="you@example.com"
                value={email}
                onChange={(e) => {
                  setEmail(e.target.value);
                  setFieldErrors((p) => ({ ...p, email: "" }));
                }}
                className={`bg-background border-input ${fieldErrors.email ? "border-destructive focus-visible:ring-destructive" : ""}`}
              />
              <FieldError msg={fieldErrors.email} />
            </div>

            {/* Password */}
            <div className="space-y-1">
              <div className="flex items-center justify-between">
                <Label htmlFor="password" className="text-foreground flex items-center gap-2">
                  <Key className="h-4 w-4 text-primary" /> Password
                </Label>
                <Link href="/forgot-password" className="text-xs text-primary hover:underline">
                  Forgot Password?
                </Link>
              </div>
              <div className="relative">
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => {
                    setPassword(e.target.value);
                    setFieldErrors((p) => ({ ...p, password: "" }));
                  }}
                  className={`bg-background border-input pr-10 ${fieldErrors.password ? "border-destructive focus-visible:ring-destructive" : ""}`}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword((v) => !v)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                  tabIndex={-1}
                >
                  {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
              <FieldError msg={fieldErrors.password} />
            </div>

            <Button
              type="submit"
              className="w-full bg-primary hover:bg-primary/90 text-primary-foreground font-medium h-10 shadow-sm"
              disabled={isPending}
            >
              {isPending ? "Signing in..." : "Sign In"}
            </Button>
          </form>
        </CardContent>

        <CardFooter className="flex flex-col space-y-2 border-t border-border pt-4">
          <p className="text-xs text-muted-foreground">
            Don't have an account?{" "}
            <Link href="/register" className="text-primary hover:underline font-medium">
              Sign Up
            </Link>
          </p>
        </CardFooter>
      </Card>
    </div>
  );
}
