
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation } from '@tanstack/react-query';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { apiRequest } from '@/lib/queryClient';
import { useToast } from '@/hooks/use-toast';

const changePasswordSchema = z.object({
    currentPassword: z.string().min(1, "auth.currentPasswordRequired"),
    newPassword: z.string().min(6, "auth.passwordMinLength"),
    confirmNewPassword: z.string(),
}).refine((data) => data.newPassword === data.confirmNewPassword, {
    message: "validation.passwordMatch",
    path: ["confirmNewPassword"],
});

type ChangePasswordFormValues = z.infer<typeof changePasswordSchema>;

interface ChangePasswordModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
}

export function ChangePasswordModal({ open, onOpenChange }: ChangePasswordModalProps) {
    const { t } = useTranslation();
    const { toast } = useToast();

    const form = useForm<ChangePasswordFormValues>({
        resolver: zodResolver(changePasswordSchema),
        defaultValues: {
            currentPassword: '',
            newPassword: '',
            confirmNewPassword: '',
        },
    });

    const mutation = useMutation({
        mutationFn: async (data: ChangePasswordFormValues) => {
            const res = await apiRequest("PATCH", "/api/user/password", {
                currentPassword: data.currentPassword,
                newPassword: data.newPassword,
            });
            if (!res.ok) {
                const text = await res.text();
                throw new Error(text || "Failed to change password");
            }
            return res.json();
        },
        onSuccess: () => {
            toast({ title: t('auth.passwordChangedSuccess') });
            form.reset();
            onOpenChange(false);
        },
        onError: (error: Error) => {
            // If error mentions current password, set field error
            if (error.message.toLowerCase().includes("current password")) {
                form.setError("currentPassword", { message: t('auth.incorrectCurrentPassword') });
            } else {
                toast({
                    title: t('auth.changePasswordFailed'),
                    description: error.message,
                    variant: "destructive",
                });
            }
        },
    });

    const onSubmit = (data: ChangePasswordFormValues) => {
        mutation.mutate(data);
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="w-[95vw] max-w-lg sm:max-w-md p-4 sm:p-6">
                <DialogHeader>
                    <DialogTitle>{t('auth.changePassword')}</DialogTitle>
                    <DialogDescription>
                        {t('auth.changePasswordDesc')}
                    </DialogDescription>
                </DialogHeader>

                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                        <FormField
                            control={form.control}
                            name="currentPassword"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{t('auth.currentPassword')}</FormLabel>
                                    <FormControl>
                                        <Input {...field} type="password" />
                                    </FormControl>
                                    <FormMessage>
                                        {form.formState.errors.currentPassword?.message && t(form.formState.errors.currentPassword.message)}
                                    </FormMessage>
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="newPassword"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{t('auth.newPassword')}</FormLabel>
                                    <FormControl>
                                        <Input {...field} type="password" />
                                    </FormControl>
                                    <FormMessage>
                                        {form.formState.errors.newPassword?.message && t(form.formState.errors.newPassword.message)}
                                    </FormMessage>
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="confirmNewPassword"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{t('auth.confirmPassword')}</FormLabel>
                                    <FormControl>
                                        <Input {...field} type="password" />
                                    </FormControl>
                                    <FormMessage>
                                        {form.formState.errors.confirmNewPassword?.message && t(form.formState.errors.confirmNewPassword.message)}
                                    </FormMessage>
                                </FormItem>
                            )}
                        />

                        <div className="flex justify-end gap-2">
                            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                                {t('common.cancel')}
                            </Button>
                            <Button type="submit" disabled={mutation.isPending}>
                                {mutation.isPending ? t('auth.changing') : t('auth.changePassword')}
                            </Button>
                        </div>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    );
}
