import { useMutation } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import { KeyRound, Lock, Mail, ShieldHalf } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Button } from "../../components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "../../components/ui/card";
import { Input } from "../../components/ui/input";
import { Label } from "../../components/ui/label";
import { login } from "../../lib/adminApi";
import { t } from "../../lib/i18n";

function LoginPage() {
  const navigate = useNavigate();
  const [loginId, setLoginId] = useState("");
  const [password, setPassword] = useState("");

  const loginMutation = useMutation({
    mutationFn: () => login({ loginId, password }),
    onSuccess: (data) => {
      window.localStorage.setItem("admin_session", data.sessionToken);
      navigate("/");
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    loginMutation.mutate();
  };

  const errorMsg = (loginMutation.error as AxiosError<{ error?: string }>)?.response
    ?.data?.error;

  return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4 py-12 sm:px-6 lg:px-8 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-primary/10 via-background to-background">
      <div className="w-full max-w-md space-y-8">
        <div className="flex flex-col items-center justify-center space-y-4 text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-primary/15 text-primary shadow-[0_20px_50px_rgba(54,211,153,0.3)]">
            <ShieldHalf size={32} />
          </div>
          <div className="space-y-2">
            <h1 className="text-3xl font-bold tracking-tight">Baron SSO</h1>
            <p className="text-sm text-muted-foreground uppercase tracking-[0.2em]">
              Admin Control Plane
            </p>
          </div>
        </div>

        <Card className="border-primary/20 bg-card/50 backdrop-blur-xl shadow-2xl">
          <CardHeader className="space-y-1">
            <CardTitle className="text-2xl flex items-center gap-2">
                <KeyRound size={20} className="text-primary" />
                Sign in
            </CardTitle>
            <CardDescription>
              관리자 계정 정보를 입력하여 로그인하세요.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="loginId">ID (Email)</Label>
                <div className="relative">
                  <Mail className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                  <Input
                    id="loginId"
                    type="email"
                    placeholder="admin@baron.co.kr"
                    className="pl-10"
                    value={loginId}
                    onChange={(e) => setLoginId(e.target.value)}
                    required
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="password">Password</Label>
                <div className="relative">
                  <Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                  <Input
                    id="password"
                    type="password"
                    className="pl-10"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                  />
                </div>
              </div>

              {errorMsg && (
                <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive animate-in fade-in zoom-in duration-200">
                  {errorMsg}
                </div>
              )}

              <Button 
                type="submit" 
                className="w-full h-11 text-base font-semibold"
                disabled={loginMutation.isPending}
              >
                {loginMutation.isPending ? "Signing in..." : "Login to Dashboard"}
              </Button>
            </form>
          </CardContent>
        </Card>

        <p className="px-8 text-center text-sm text-muted-foreground">
          인증 정보가 없거나 로그인이 되지 않는 경우<br />
          시스템 관리자에게 문의하세요.
        </p>
      </div>
    </div>
  );
}

export default LoginPage;
