import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import {
    Form,
    FormControl,
    FormDescription,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Checkbox } from "@/components/ui/checkbox"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { userService } from "@/services/userService"
import type { User } from "@/types/api"
import { useEffect } from "react"
import { showToast } from "@/lib/sweetalert"

const userSchema = z.object({
    email: z.string().email("Geçerli bir e-posta adresi giriniz."),
    user_name: z.string().min(2, "Kullanıcı adı en az 2 karakter olmalıdır."),
    password: z.string().optional(),
    email_verified: z.boolean().optional(),
    roles: z.array(z.string()).optional(),
})

type UserFormValues = z.infer<typeof userSchema>

interface UserFormProps {
    user?: User
    onSuccess: () => void
}

export function UserForm({ user, onSuccess }: UserFormProps) {
    const queryClient = useQueryClient()
    const isEdit = !!user

    const form = useForm<UserFormValues>({
        resolver: zodResolver(userSchema),
        defaultValues: {
            email: user?.email || "",
            user_name: user?.user_name || "",
            password: "",
            email_verified: user?.email_verified || false,
            roles: user?.roles?.map(r => r.name) || [],
        },
    })

    // Reset form when user prop changes
    useEffect(() => {
        if (user) {
            form.reset({
                email: user.email,
                user_name: user.user_name,
                password: "",
                email_verified: user.email_verified,
                roles: user.roles?.map(r => r.name) || [],
            })
        } else {
            form.reset({
                email: "",
                user_name: "",
                password: "",
                email_verified: false,
                roles: [],
            })
        }
    }, [user, form])

    const createMutation = useMutation({
        mutationFn: userService.create,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        onSuccess: () => {
            showToast("Kullanıcı başarıyla oluşturuldu.", "success")
            queryClient.invalidateQueries({ queryKey: ["users"] })
            onSuccess()
        },
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        onError: (error: any) => {
            showToast(error.response?.data?.message || "Kullanıcı oluşturulurken bir hata oluştu.", "error")
        }
    })

    const updateMutation = useMutation({
        mutationFn: (data: Partial<User>) => userService.update(user!.id, data),
        onSuccess: () => {
            showToast("Kullanıcı başarıyla güncellendi.", "success")
            queryClient.invalidateQueries({ queryKey: ["users"] })
            onSuccess()
        },
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        onError: (error: any) => {
            showToast(error.response?.data?.message || "Kullanıcı güncellenirken bir hata oluştu.", "error")
        }
    })

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function onSubmit(data: any) {
        if (isEdit) {
            // If password is empty, don't send it for update
            const { password, ...rest } = data
            const updateData: any = rest
            if (password && password.length > 0) {
                updateData.password = password
            }

            updateMutation.mutate(updateData)
        } else {
            if (!data.password || data.password.length < 6) {
                form.setError("password", { message: "Yeni kullanıcı için en az 6 karakterli şifre gereklidir." })
                return
            }
            createMutation.mutate(data)
        }
    }

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="email"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>E-posta</FormLabel>
                            <FormControl>
                                <Input placeholder="ornek@domain.com" {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="user_name"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Kullanıcı Adı</FormLabel>
                            <FormControl>
                                <Input placeholder="kullaniciadi" {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="password"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Şifre {isEdit && "(Boş bırakılırsa değişmez)"}</FormLabel>
                            <FormControl>
                                <Input type="password" placeholder="******" {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="email_verified"
                    render={({ field }) => (
                        <FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">
                            <FormControl>
                                <Checkbox
                                    checked={field.value as boolean}
                                    onCheckedChange={field.onChange}
                                />
                            </FormControl>
                            <div className="space-y-1 leading-none">
                                <FormLabel>
                                    E-posta Doğrulanmış
                                </FormLabel>
                                <FormDescription>
                                    Kullanıcının e-posta adresi doğrulanmış olarak işaretlensin mi?
                                </FormDescription>
                            </div>
                        </FormItem>
                    )}
                />
                <Button type="submit" disabled={createMutation.isPending || updateMutation.isPending}>
                    {isEdit ? "Güncelle" : "Oluştur"}
                </Button>
            </form>
        </Form>
    )
}
