'use client';

import { useTranslations } from 'next-intl';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter, usePathname, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { api } from '@/lib/api';
import { useMutation } from '@tanstack/react-query';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Lock, Mail } from 'lucide-react';
import { useState } from 'react';

export default function ResetPasswordPage() {
  const t = useTranslations('Auth');
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const locale = pathname.startsWith('/en') ? 'en' : 'vi';
  const tokenFromUrl = searchParams.get('token') || '';
  const [successMessage, setSuccessMessage] = useState<string>('');

  const formSchema = z.object({
    email: z.string().email({ message: t('invalidEmail') }),
    token: z.string().min(1, { message: t('tokenRequired') }),
    newPassword: z.string().min(8, { message: t('passwordMinLength') }),
    confirmPassword: z.string().min(1, { message: t('confirmPasswordRequired') }),
  }).refine((data) => data.newPassword === data.confirmPassword, {
    message: t('passwordsMustMatch'),
    path: ['confirmPassword'],
  });

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: { email: '', token: tokenFromUrl, newPassword: '', confirmPassword: '' },
  });

  const resetPasswordMutation = useMutation({
    mutationFn: async (values: z.infer<typeof formSchema>) => {
      const response = await api.post('/auth/reset-password', values);
      return response.data;
    },
    onSuccess: (data) => {
      setSuccessMessage(data.message || t('resetPasswordSuccess'));
      setTimeout(() => {
        router.push(`/${locale}/auth/login`);
      }, 2500);
    },
  });
  const resetError = resetPasswordMutation.error as { response?: { data?: { message?: string } } } | null;

  return (
    <div className="min-h-screen bg-[#0f1117] flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-black">
            <span className="bg-gradient-to-r from-violet-500 to-cyan-400 bg-clip-text text-transparent">SHOP</span>
            <span className="text-white">MMO</span>
          </h1>
          <p className="text-gray-400 mt-2 text-sm">{locale === 'vi' ? 'Marketplace Sản phẩm Số' : 'Digital Product Marketplace'}</p>
        </div>

        <div className="rounded-2xl border border-white/10 bg-white/5 backdrop-blur p-8 shadow-2xl">
          <h2 className="text-xl font-bold text-white mb-6">{t('resetPassword')}</h2>

          {successMessage ? (
            <div className="mb-4 rounded-lg bg-emerald-500/10 border border-emerald-500/20 p-3 text-sm text-emerald-200">
              {successMessage}
            </div>
          ) : null}

          {resetPasswordMutation.isError && (
            <div className="mb-4 rounded-lg bg-red-500/10 border border-red-500/20 p-3 text-sm text-red-400">
              {resetError?.response?.data?.message || t('resetPasswordError')}
            </div>
          )}

          <Form {...form}>
            <form onSubmit={form.handleSubmit((values) => resetPasswordMutation.mutate(values))} className="space-y-4">
              <FormField control={form.control} name="email" render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-gray-300">{t('email')}</FormLabel>
                  <FormControl>
                    <div className="relative">
                      <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-500" />
                      <Input
                        placeholder="you@example.com"
                        {...field}
                        className="pl-9 bg-white/5 border-white/10 text-white placeholder:text-gray-600 focus:border-violet-500"
                      />
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )} />

              <input type="hidden" {...form.register('token')} value={tokenFromUrl} readOnly />

              <FormField control={form.control} name="newPassword" render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-gray-300">{t('newPassword')}</FormLabel>
                  <FormControl>
                    <div className="relative">
                      <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-500" />
                      <Input
                        type="password"
                        placeholder={t('newPassword')}
                        {...field}
                        className="pl-9 bg-white/5 border-white/10 text-white placeholder:text-gray-600 focus:border-violet-500"
                      />
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )} />

              <FormField control={form.control} name="confirmPassword" render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-gray-300">{t('confirmPassword')}</FormLabel>
                  <FormControl>
                    <Input
                      type="password"
                      placeholder={t('confirmPassword')}
                      {...field}
                      className="bg-white/5 border-white/10 text-white focus:border-violet-500"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )} />

              <Button type="submit" className="w-full h-11 bg-gradient-to-r from-violet-600 to-cyan-600 hover:opacity-90 text-white font-semibold" disabled={resetPasswordMutation.isPending}>
                {resetPasswordMutation.isPending ? t('resettingPassword') : t('resetPassword')}
              </Button>
            </form>
          </Form>

          <div className="mt-6 text-center text-sm text-gray-500">
            <Link href={`/${locale}/auth/login`} className="text-violet-400 hover:text-violet-300 font-medium">
              {t('backToLogin')}
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
