import { useState } from 'react';
import { Link, Navigate, useNavigate } from 'react-router-dom';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { LoaderCircle, LockKeyhole, Mail, UserCircle2, UserPlus } 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 registerSchema = z
  .object({
    username: z.string().min(2, '用户名至少需要 2 个字符').max(20, '用户名最多 20 个字符'),
    email: z.string().min(1, '请输入邮箱').email('请输入有效的邮箱地址'),
    password: z.string().min(6, '密码至少需要 6 位'),
    confirmPassword: z.string().min(1, '请再次输入密码'),
  })
  .refine(values => values.password === values.confirmPassword, {
    message: '两次输入的密码不一致',
    path: ['confirmPassword'],
  });

type RegisterFormValues = z.infer<typeof registerSchema>;

export default function Register() {
  const navigate = useNavigate();
  const { isAuthenticated, isBootstrapping, register } = useAuth();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const form = useForm<RegisterFormValues>({
    resolver: zodResolver(registerSchema),
    defaultValues: {
      username: '',
      email: '',
      password: '',
      confirmPassword: '',
    },
  });

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

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

    try {
      // values.email 仅用于前端二次确认；后端 register 服务由 username 推导邮箱地址。
      await register({
        username: values.username,
        password: values.password,
      });
      toast.success('注册成功');
      navigate('/', { 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)]">
            <UserPlus 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="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-slate-700">邮箱</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Mail 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="email"
                          {...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="请输入至少 6 位密码"
                          autoComplete="new-password"
                          {...field}
                        />
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="confirmPassword"
                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="new-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="/login" className="font-medium text-[#2563eb] hover:text-[#1d4ed8] hover:underline">
              返回登录
            </Link>
          </p>
        </CardContent>
      </Card>
    </div>
  );
}
