'use client';

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useEffect } from 'react';
import UseConvertToClient from '../../hooks/UseConvertToClient';
import { toast } from 'sonner';

const formSchema = z.object({
    password: z.string().min(1, 'Password is required'),
    account_type_id: z.string({
        required_error: 'Please select an account type',
    }),
});

interface ConvertToClientProps {
    userId: number | null;
    isOpen?: boolean;
    onClose?: () => void;
    onSuccess?: () => void;
}

export default function ConvertToClient({
    userId,
    isOpen = false,
    onClose,
    onSuccess,
}: ConvertToClientProps) {
    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            password: '',
            account_type_id: '',
        },
    });
 const {mutate ,isPending} = UseConvertToClient(); 
    useEffect(() => {
        if (isOpen) {
            form.reset({
                password: '',
                account_type_id: '',
            });
        }
    }, [isOpen, form]);

    const onSubmit = (values: z.infer<typeof formSchema>) => {
        if (!userId) return;
        const payload = {
            registration_id: userId,
            account_type_id: Number(values.account_type_id),
            password: values.password,
        };
        mutate(payload , {
            onSuccess : () => {
                toast.success('User converted successfully');
                if (onSuccess) {
                    onSuccess();
                }
                if (onClose) {
                    onClose();
                }
            },
            onError : () => {
                toast.error('Failed to convert user');
            }
        });  
    };
    const handleOpenChange = (open: boolean) => {
        if (!open && onClose) {
            onClose();
        }
    };
    return (
        <Dialog open={isOpen} onOpenChange={handleOpenChange}>
            <DialogContent className="sm:max-w-[425px]">
                <DialogHeader>
                    <DialogTitle>Convert To Client</DialogTitle>
                </DialogHeader>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                        <FormField
                            control={form.control}
                            name="password"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Password</FormLabel>
                                    <FormControl>
                                        <Input type="password" placeholder="Enter password" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            control={form.control}
                            name="account_type_id"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Account Type</FormLabel>
                                    <Select
                                        onValueChange={field.onChange}
                                        defaultValue={field.value}
                                    >
                                        <FormControl>
                                            <SelectTrigger>
                                                <SelectValue placeholder="Select account type" />
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            <SelectItem value="2">Brand</SelectItem>
                                            <SelectItem value="3">Influencer</SelectItem>
                                        </SelectContent>
                                    </Select>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <div className="flex justify-end">
                            <Button type="submit"> {isPending ? 'Converting...' : 'Convert'}</Button>
                        </div>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    );
}