import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table"
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Checkbox } from "@/components/ui/checkbox"
import { useToast } from "@/components/ui/use-toast"
import { zodResolver } from "@hookform/resolvers/zod"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { Pencil, Plus, Trash2 } from "lucide-react"
import { useState } from "react"
import { useForm } from "react-hook-form"
import * as z from "zod"
import {
    createPostTag,
    deletePostTag,
    getPostTags,
    updatePostTag,
} from "@/features/blog/services/blog.service"
import type { PostTag } from "@/features/blog/types"

const formSchema = z.object({
    tag: z.string().min(1, "Etiket adı zorunludur"),
    is_active: z.boolean(),
})

type PostTagFormValues = z.infer<typeof formSchema>

export default function PostTagsPage() {
    const { toast } = useToast()
    const queryClient = useQueryClient()
    const [isOpen, setIsOpen] = useState(false)
    const [editingItem, setEditingItem] = useState<PostTag | null>(null)

    const { data: tags, isLoading } = useQuery({
        queryKey: ["postTags"],
        queryFn: () => getPostTags(true),
    })

    const form = useForm<PostTagFormValues>({
        resolver: zodResolver(formSchema) as any,
        defaultValues: {
            tag: "",
            is_active: true,
        },
    })

    const createMutation = useMutation({
        mutationFn: (data: z.infer<typeof formSchema>) => createPostTag(data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["postTags"] })
            toast({ title: "Başarılı", description: "Etiket oluşturuldu" })
            setIsOpen(false)
            form.reset()
        },
        onError: (error: any) => {
            toast({
                title: "Hata",
                description: error.response?.data?.error || "Bir hata oluştu",
                variant: "destructive",
            })
        },
    })

    const updateMutation = useMutation({
        mutationFn: ({ id, data }: { id: string; data: z.infer<typeof formSchema> }) =>
            updatePostTag(id, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["postTags"] })
            toast({ title: "Başarılı", description: "Etiket güncellendi" })
            setIsOpen(false)
            setEditingItem(null)
            form.reset()
        },
        onError: (error: any) => {
            toast({
                title: "Hata",
                description: error.response?.data?.error || "Bir hata oluştu",
                variant: "destructive",
            })
        },
    })

    const deleteMutation = useMutation({
        mutationFn: deletePostTag,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["postTags"] })
            toast({ title: "Başarılı", description: "Etiket silindi" })
        },
        onError: (error: any) => {
            toast({
                title: "Hata",
                description: error.response?.data?.error || "Bir hata oluştu",
                variant: "destructive",
            })
        },
    })

    function onSubmit(values: z.infer<typeof formSchema>) {
        if (editingItem) {
            updateMutation.mutate({ id: editingItem.id, data: values })
        } else {
            createMutation.mutate(values)
        }
    }

    const handleEdit = (item: PostTag) => {
        setEditingItem(item)
        form.reset({
            tag: item.tag,
            is_active: item.is_active,
        })
        setIsOpen(true)
    }

    const handleDelete = (id: string) => {
        if (confirm("Bu etiketi silmek istediğinize emin misiniz?")) {
            deleteMutation.mutate(id)
        }
    }

    const handleCreateOpen = () => {
        setEditingItem(null)
        form.reset({
            tag: "",
            is_active: true,
        })
        setIsOpen(true)
    }

    if (isLoading) return <div>Yükleniyor...</div>

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h2 className="text-3xl font-bold tracking-tight">Etiketler</h2>
                <Dialog open={isOpen} onOpenChange={setIsOpen}>
                    <DialogTrigger asChild>
                        <Button onClick={handleCreateOpen}>
                            <Plus className="mr-2 h-4 w-4" /> Yeni Etiket
                        </Button>
                    </DialogTrigger>
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>
                                {editingItem ? "Etiketi Düzenle" : "Yeni Etiket Ekle"}
                            </DialogTitle>
                        </DialogHeader>
                        <Form {...form}>
                            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                                <FormField
                                    control={form.control}
                                    name="tag"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Etiket Adı</FormLabel>
                                            <FormControl>
                                                <Input placeholder="Örn: Teknoloji" {...field} />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="is_active"
                                    render={({ field }) => (
                                        <FormItem className="flex flex-row items-center space-x-3 space-y-0 rounded-md border p-4">
                                            <FormControl>
                                                <Checkbox
                                                    checked={field.value}
                                                    onCheckedChange={field.onChange}
                                                />
                                            </FormControl>
                                            <div className="space-y-1 leading-none">
                                                <FormLabel>Aktif</FormLabel>
                                            </div>
                                        </FormItem>
                                    )}
                                />

                                <Button type="submit" className="w-full">
                                    {editingItem ? "Güncelle" : "Oluştur"}
                                </Button>
                            </form>
                        </Form>
                    </DialogContent>
                </Dialog>
            </div>

            <Card>
                <CardHeader>
                    <CardTitle>Etiket Listesi</CardTitle>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Etiket</TableHead>
                                <TableHead>Durum</TableHead>
                                <TableHead className="text-right">İşlemler</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {tags?.map((item) => (
                                <TableRow key={item.id}>
                                    <TableCell className="font-medium">{item.tag}</TableCell>
                                    <TableCell>
                                        <span
                                            className={`px-2 py-1 rounded text-xs ${item.is_active
                                                ? "bg-green-100 text-green-800"
                                                : "bg-red-100 text-red-800"
                                                }`}
                                        >
                                            {item.is_active ? "Aktif" : "Pasif"}
                                        </span>
                                    </TableCell>
                                    <TableCell className="text-right space-x-2">
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            onClick={() => handleEdit(item)}
                                        >
                                            <Pencil className="h-4 w-4" />
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            onClick={() => handleDelete(item.id)}
                                        >
                                            <Trash2 className="h-4 w-4 text-red-500" />
                                        </Button>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </CardContent>
            </Card>
        </div>
    )
}
