import { useState } from 'react';
import type { LoginPayload } from '@/types';
import type { Location } from 'react-router-dom';
import { Link, Navigate, useLocation, useNavigate } from 'react-router-dom';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { LoaderCircle, LockKeyhole, UserCircle2 } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { useAuth } from '@/hooks/useAuth';

const loginSchema = z.object({
  username: z.string().min(1, '请输入用户名'),
  password: z.string().min(1, '请输入密码'),
});

type LoginFormValues = z.infer<typeof loginSchema>;

function getRedirectPath(location: ReturnType<typeof useLocation>) {
  const navigationState = location.state as { from?: Location } | null;
  const from = navigationState?.from;

  if (!from) {
    return '/';
  }

  return `${from.pathname}${from.search}${from.hash}`;
}

export default function Login() {
  const location = useLocation();
  const navigate = useNavigate();
  const { isAuthenticated, isBootstrapping, login } = useAuth();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const redirectPath = getRedirectPath(location);
  const form = useForm<LoginFormValues>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      username: '',
      password: '',
    },
  });

  if (!isBootstrapping && isAuthenticated) {
    return <Navigate to={redirectPath} replace />;
  }

  async function handleSubmit(values: LoginFormValues) {
    setIsSubmitting(true);

    try {
      await login(values as LoginPayload);
      toast.success('登录成功');
      navigate(redirectPath, { replace: true });
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '登录失败');
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-[#f8fafc] px-6 py-10">
      <Card className="w-full max-w-[420px] rounded-[24px] border border-[#dbe7fb] bg-white p-10 shadow-[0_28px_60px_-36px_rgba(37,99,235,0.18)] sm:w-[420px]">
        <CardHeader className="space-y-4 px-0 pb-8 pt-0 text-center">
          <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-[linear-gradient(135deg,#2563eb_0%,#3b82f6_55%,#60a5fa_100%)] text-white shadow-[0_18px_32px_-20px_rgba(37,99,235,0.55)] transition-all duration-300 hover:-translate-y-0.5 hover:shadow-[0_22px_38px_-22px_rgba(37,99,235,0.62)]">
            <LockKeyhole className="h-6 w-6" />
          </div>
          <CardTitle className="text-xl font-bold tracking-[0.02em] text-[#1d4ed8]">登录系统</CardTitle>
        </CardHeader>

        <CardContent className="space-y-6 px-0 pb-0">
          <Form {...form}>
            <form className="space-y-5" onSubmit={form.handleSubmit(handleSubmit)}>
              <FormField
                control={form.control}
                name="username"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-slate-700">用户名</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <UserCircle2 className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                        <Input
                          className="h-11 rounded-xl border-gray-200 bg-white pl-10 text-slate-800 transition-all duration-200 hover:border-[#bfdbfe] hover:shadow-[0_10px_18px_-16px_rgba(37,99,235,0.35)] focus-visible:border-[#3b82f6] focus-visible:ring-1 focus-visible:ring-[#93c5fd]/60"
                          placeholder="请输入用户名"
                          autoComplete="username"
                          {...field}
                        />
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-slate-700">密码</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <LockKeyhole className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                        <Input
                          className="h-11 rounded-xl border-gray-200 bg-white pl-10 text-slate-800 transition-all duration-200 hover:border-[#bfdbfe] hover:shadow-[0_10px_18px_-16px_rgba(37,99,235,0.35)] focus-visible:border-[#3b82f6] focus-visible:ring-1 focus-visible:ring-[#93c5fd]/60"
                          type="password"
                          placeholder="请输入密码"
                          autoComplete="current-password"
                          {...field}
                        />
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <Button
                className="h-11 w-full rounded-xl bg-[#2563eb] font-bold text-white transition-all duration-200 hover:bg-[#1d4ed8] hover:shadow-[0_16px_30px_-20px_rgba(37,99,235,0.58)]"
                type="submit"
                disabled={isSubmitting || isBootstrapping}
              >
                {isSubmitting ? <LoaderCircle className="mr-2 h-4 w-4 animate-spin" /> : null}
                进入系统
              </Button>
            </form>
          </Form>

          <p className="text-center text-sm text-slate-500">
            还没有账号？{' '}
            <Link to="/register" className="font-medium text-[#2563eb] hover:text-[#1d4ed8] hover:underline">
              立即注册
            </Link>
          </p>
        </CardContent>
      </Card>
    </div>
  );
}