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 { useCreateCorsRule, useUpdateCorsRule } from "../hooks/useCors"
import type { CorsRule } from "@/types/api"
import { useEffect } from "react"
import { showToast } from "@/lib/sweetalert"

const corsSchema = z.object({
    origin: z.string().min(1, "Origin (Kaynak) zorunludur."),
    description: z.string().optional(),
    is_active: z.boolean().default(true),
})

type CorsFormValues = z.infer<typeof corsSchema>

interface CorsFormProps {
    type: 'whitelist' | 'blacklist'
    rule?: CorsRule
    onSuccess: () => void
}

export function CorsForm({ type, rule, onSuccess }: CorsFormProps) {
    const createMutation = useCreateCorsRule(type)
    const updateMutation = useUpdateCorsRule(type)
    const isEdit = !!rule

    const form = useForm<CorsFormValues>({
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        resolver: zodResolver(corsSchema) as any,
        defaultValues: {
            origin: rule?.origin || "",
            description: rule?.description || "",
            is_active: rule?.is_active ?? true,
        },
    })

    useEffect(() => {
        if (rule) {
            form.reset({
                origin: rule.origin,
                description: rule.description || "",
                is_active: rule.is_active,
            })
        } else {
            form.reset({
                origin: "",
                description: "",
                is_active: true,
            })
        }
    }, [rule, form])

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function onSubmit(data: any) {
        if (isEdit) {
            updateMutation.mutate({ id: rule!.id, data }, {
                onSuccess: () => {
                    showToast(`${type === 'whitelist' ? 'Whitelist' : 'Blacklist'} kuralı güncellendi.`, 'success')
                    onSuccess()
                },
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                onError: (error: any) => {
                    showToast(error.response?.data?.message || "Kural güncellenirken hata oluştu.", "error")
                }
            })
        } else {
            createMutation.mutate({ ...data }, {
                onSuccess: () => {
                    showToast(`${type === 'whitelist' ? 'Whitelist' : 'Blacklist'} kuralı eklendi.`, 'success')
                    onSuccess()
                },
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                onError: (error: any) => {
                    showToast(error.response?.data?.message || "Kural eklenirken hata oluştu.", "error")
                }
            })
        }
    }

    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="origin"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Origin (Domain/IP)</FormLabel>
                            <FormControl>
                                <Input placeholder="https://ornek.com veya *" {...field} />
                            </FormControl>
                            <FormDescription>
                                İzin verilen veya engellenen kaynak adresi.
                            </FormDescription>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="description"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Açıklama</FormLabel>
                            <FormControl>
                                <Input placeholder="Örn: Mobil Uygulama Servisi" {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="is_active"
                    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>
                                    Aktif
                                </FormLabel>
                                <FormDescription>
                                    Bu kural şu an geçerli olsun mu?
                                </FormDescription>
                            </div>
                        </FormItem>
                    )}
                />
                <Button type="submit" disabled={createMutation.isPending || updateMutation.isPending}>
                    {isEdit ? "Güncelle" : "Ekle"}
                </Button>
            </form>
        </Form>
    )
}
