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 { Textarea } from "@/components/ui/textarea"
import { useCreateContact, useUpdateContact } from "../hooks/useContacts"
import { useTags } from "@/features/tags/hooks/useTags"
import type { Contact, Tag } from "@/types/api"
import { useEffect } from "react"
import { showToast } from "@/lib/sweetalert"

const contactSchema = z.object({
  name: z.string().min(1, "İsim zorunludur."),
  email: z.string().email("Geçerli bir e-posta adresi giriniz."),
  phone: z.string().optional(),
  message: z.string().optional(),
  is_active: z.boolean().default(true),
  tag_ids: z.array(z.string()).optional(),
})

type ContactFormValues = z.infer<typeof contactSchema>

interface ContactFormProps {
  contact?: Contact
  onSuccess: () => void
}

export function ContactForm({ contact, onSuccess }: ContactFormProps) {
  const createMutation = useCreateContact()
  const updateMutation = useUpdateContact()
  const isEdit = !!contact

  // Tag Selection Data
  const { data: tagsData } = useTags(1, 100)
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const allTags: Tag[] = Array.isArray(tagsData) ? tagsData : (tagsData as any)?.data || (tagsData as any)?.tags || []

  const form = useForm<ContactFormValues>({
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    resolver: zodResolver(contactSchema) as any,
    defaultValues: {
      name: contact?.name || "",
      email: contact?.email || "",
      phone: contact?.phone || "",
      message: contact?.message || "",
      is_active: contact?.is_active ?? true,
      tag_ids: contact?.tags?.map(t => t.id) || [],
    },
  })

  useEffect(() => {
    if (contact) {
      form.reset({
        name: contact.name,
        email: contact.email,
        phone: contact.phone || "",
        message: contact.message || "",
        is_active: contact.is_active,
        tag_ids: contact.tags?.map(t => t.id) || [],
      })
    } else {
      form.reset({
        name: "",
        email: "",
        phone: "",
        message: "",
        is_active: true,
        tag_ids: [],
      })
    }
  }, [contact, form])

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  function onSubmit(data: any) {
    if (isEdit) {
      updateMutation.mutate({ id: contact!.id, data }, {
        onSuccess: () => {
          showToast("Kişi başarıyla güncellendi.", "success")
          onSuccess()
        },
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        onError: (error: any) => {
          showToast(error.response?.data?.message || "Kişi güncellenirken hata oluştu.", "error")
        }
      })
    } else {
      createMutation.mutate(data, {
        onSuccess: () => {
          showToast("Kişi başarıyla oluşturuldu.", "success")
          onSuccess()
        },
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        onError: (error: any) => {
          showToast(error.response?.data?.message || "Kişi oluşturulurken 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>İsim Soyisim</FormLabel>
              <FormControl>
                <Input placeholder="Ad Soyad" {...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="email"
            render={({ field }) => (
              <FormItem>
                <FormLabel>E-posta</FormLabel>
                <FormControl>
                  <Input placeholder="ornek@email.com" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            control={form.control as any}
            name="phone"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Telefon</FormLabel>
                <FormControl>
                  <Input placeholder="+90 555..." {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <FormField
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          control={form.control as any}
          name="message"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Not / Mesaj</FormLabel>
              <FormControl>
                <Textarea placeholder="Kişi hakkında notlar..." className="resize-none" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          control={form.control as any}
          name="tag_ids"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Etiketler</FormLabel>
              <div className="grid grid-cols-2 gap-2 border p-3 rounded-md max-h-40 overflow-y-auto">
                {allTags.map((tag) => (
                  <FormItem key={tag.id} className="flex flex-row items-center space-x-2 space-y-0">
                    <FormControl>
                      <Checkbox
                        checked={field.value?.includes(tag.id)}
                        onCheckedChange={(checked) => {
                          return checked
                            ? field.onChange([...(field.value || []), tag.id])
                            : field.onChange(
                              field.value?.filter((value: string) => value !== tag.id)
                            )
                        }}
                      />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">
                      {tag.tag}
                    </FormLabel>
                  </FormItem>
                ))}
                {allTags.length === 0 && <p className="text-sm text-muted-foreground">Etiket bulunamadı.</p>}
              </div>
              <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 kişi aktif listelerde görünsün mü?
                </FormDescription>
              </div>
            </FormItem>
          )}
        />
        <Button type="submit" disabled={createMutation.isPending || updateMutation.isPending}>
          {isEdit ? "Güncelle" : "Oluştur"}
        </Button>
      </form>
    </Form>
  )
}
