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 { useCreateRateLimit, useUpdateRateLimit } from "../hooks/useRateLimit"
import type { RateLimitRule } from "@/types/api"
import { useEffect } from "react"
import { showToast } from "@/lib/sweetalert"

const rateLimitSchema = z.object({
  name: z.string().min(1, "Kural adı zorunludur."),
  description: z.string().optional(),
  max_requests: z.coerce.number().min(1, "Maksimum istek sayısı en az 1 olmalıdır."),
  window_seconds: z.coerce.number().min(1, "Periyot (saniye) en az 1 olmalıdır."),
  is_active: z.boolean().default(true),
})

type RateLimitFormValues = z.infer<typeof rateLimitSchema>

interface RateLimitFormProps {
  rule?: RateLimitRule
  onSuccess: () => void
}

export function RateLimitForm({ rule, onSuccess }: RateLimitFormProps) {
  const createMutation = useCreateRateLimit()
  const updateMutation = useUpdateRateLimit()
  const isEdit = !!rule

  const form = useForm<RateLimitFormValues>({
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    resolver: zodResolver(rateLimitSchema) as any,
    defaultValues: {
      name: rule?.name || "",
      description: rule?.description || "",
      max_requests: rule?.max_requests || 100,
      window_seconds: rule?.window_seconds || 60,
      is_active: rule?.is_active ?? true,
    },
  })

  useEffect(() => {
    if (rule) {
      form.reset({
        name: rule.name,
        description: rule.description || "",
        max_requests: rule.max_requests,
        window_seconds: rule.window_seconds,
        is_active: rule.is_active,
      })
    } else {
      form.reset({
        name: "",
        description: "",
        max_requests: 100,
        window_seconds: 60,
        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("Hız sınırı 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("Hız sınırı 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="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Kural Adı (Endpoint/Key)</FormLabel>
              <FormControl>
                <Input placeholder="Örn: login, register, api" {...field} />
              </FormControl>
              <FormDescription>Tekil tanımlayıcı ad.</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: Login endpoint rate limit" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className="grid grid-cols-2 gap-4">
          <FormField
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            control={form.control as any}
            name="max_requests"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Maks. İstek</FormLabel>
                <FormControl>
                  <Input type="number" min="1" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            control={form.control as any}
            name="window_seconds"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Süre (Saniye)</FormLabel>
                <FormControl>
                  <Input type="number" min="1" {...field} />
                </FormControl>
                <FormDescription>Pencere süresi.</FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <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>
  )
}
