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 { Textarea } from "@/components/ui/textarea"
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, useMemo } from "react"
import { useForm } from "react-hook-form"
import * as z from "zod"
import {
    createPostCategory,
    deletePostCategory,
    getPostCategories,
    updatePostCategory,
} from "@/features/blog/services/blog.service"
import type { PostCategory } from "@/features/blog/types"
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select"

const formSchema = z.object({
    title: z.string().min(1, "Başlık zorunludur"),
    keywords: z.string().min(1, "Anahtar kelimeler zorunludur"),
    description: z.string().min(1, "Açıklama zorunludur"),
    order: z.coerce.number().int(),
    parent_id: z.string().optional(),
    is_active: z.boolean(),
    // image is handled separately as File | null
})

type PostCategoryFormValues = z.infer<typeof formSchema>

export default function PostCategoriesPage() {
    const { toast } = useToast()
    const queryClient = useQueryClient()
    const [isOpen, setIsOpen] = useState(false)
    const [editingItem, setEditingItem] = useState<PostCategory | null>(null)
    const [selectedImage, setSelectedImage] = useState<File | null>(null)

    const { data: categories, isLoading } = useQuery({
        queryKey: ["postCategories"],
        queryFn: () => getPostCategories(true),
    })

    const sortedCategories = useMemo(() => {
        if (!categories) return []
        const buildHierarchy = (cats: PostCategory[], parentId: string | undefined = undefined, level = 0): (PostCategory & { level: number })[] => {
            const result: (PostCategory & { level: number })[] = []
            const children = cats
                .filter((c) => c.parent_id === parentId || (!parentId && !c.parent_id))
                .sort((a, b) => a.order - b.order)

            for (const child of children) {
                result.push({ ...child, level })
                result.push(...buildHierarchy(cats, child.id, level + 1))
            }
            return result
        }
        return buildHierarchy(categories)
    }, [categories])

    const form = useForm<PostCategoryFormValues>({
        resolver: zodResolver(formSchema) as any,
        defaultValues: {
            title: "",
            keywords: "",
            description: "",
            order: 1,
            parent_id: undefined,
            is_active: true,
        },
    })

    const createMutation = useMutation({
        mutationFn: (formData: FormData) => createPostCategory(formData),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["postCategories"] })
            toast({ title: "Başarılı", description: "Kategori oluşturuldu" })
            setIsOpen(false)
            form.reset()
            setSelectedImage(null)
        },
        onError: (error: any) => {
            toast({
                title: "Hata",
                description: error.response?.data?.error || "Bir hata oluştu",
                variant: "destructive",
            })
        },
    })

    const updateMutation = useMutation({
        mutationFn: ({ id, formData }: { id: string; formData: FormData }) =>
            updatePostCategory(id, formData),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["postCategories"] })
            toast({ title: "Başarılı", description: "Kategori güncellendi" })
            setIsOpen(false)
            setEditingItem(null)
            form.reset()
            setSelectedImage(null)
        },
        onError: (error: any) => {
            toast({
                title: "Hata",
                description: error.response?.data?.error || "Bir hata oluştu",
                variant: "destructive",
            })
        },
    })

    const deleteMutation = useMutation({
        mutationFn: deletePostCategory,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["postCategories"] })
            toast({ title: "Başarılı", description: "Kategori 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>) {
        const formData = new FormData()
        formData.append("title", values.title)
        formData.append("keywords", values.keywords)
        formData.append("description", values.description)
        formData.append("order", values.order.toString())
        formData.append("is_active", values.is_active.toString())

        if (values.parent_id && values.parent_id !== "none") {
            formData.append("parent_id", values.parent_id)
        }

        if (selectedImage) {
            formData.append("image", selectedImage)
        }

        if (editingItem) {
            updateMutation.mutate({ id: editingItem.id, formData })
        } else {
            createMutation.mutate(formData)
        }
    }

    const handleEdit = (item: PostCategory) => {
        setEditingItem(item)
        form.reset({
            title: item.title,
            keywords: item.keywords,
            description: item.description,
            order: item.order,
            parent_id: item.parent_id,
            is_active: item.is_active,
        })
        setIsOpen(true)
    }

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

    const handleCreateOpen = () => {
        setEditingItem(null)
        form.reset({
            title: "",
            keywords: "",
            description: "",
            order: 1,
            parent_id: undefined,
            is_active: true,
        })
        setSelectedImage(null)
        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">Kategoriler</h2>
                <Dialog open={isOpen} onOpenChange={setIsOpen}>
                    <DialogTrigger asChild>
                        <Button onClick={handleCreateOpen}>
                            <Plus className="mr-2 h-4 w-4" /> Yeni Kategori
                        </Button>
                    </DialogTrigger>
                    <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
                        <DialogHeader>
                            <DialogTitle>
                                {editingItem ? "Kategoriyi Düzenle" : "Yeni Kategori Ekle"}
                            </DialogTitle>
                        </DialogHeader>
                        <Form {...form}>
                            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                                <FormField
                                    control={form.control}
                                    name="title"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Başlık</FormLabel>
                                            <FormControl>
                                                <Input placeholder="Kategori Başlığı" {...field} />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="keywords"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Anahtar Kelimeler</FormLabel>
                                            <FormControl>
                                                <Input placeholder="Virgülle ayırın" {...field} />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="description"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Açıklama</FormLabel>
                                            <FormControl>
                                                <Textarea placeholder="Kısa açıklama" {...field} />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <div className="grid grid-cols-2 gap-4">
                                    <FormField
                                        control={form.control}
                                        name="order"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>Sıra</FormLabel>
                                                <FormControl>
                                                    <Input type="number" {...field} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="parent_id"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>Üst Kategori</FormLabel>
                                                <Select
                                                    onValueChange={field.onChange}
                                                    defaultValue={field.value}
                                                >
                                                    <FormControl>
                                                        <SelectTrigger>
                                                            <SelectValue placeholder="Seçiniz (Opsiyonel)" />
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        <SelectItem value="none">-- Yok --</SelectItem>
                                                        {categories?.map((cat) => (
                                                            <SelectItem key={cat.id} value={cat.id}>
                                                                {cat.title}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>

                                <div className="space-y-2">
                                    <label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
                                        Resim
                                    </label>
                                    <Input
                                        type="file"
                                        accept="image/*"
                                        onChange={(e) =>
                                            setSelectedImage(
                                                e.target.files ? e.target.files[0] : null
                                            )
                                        }
                                    />
                                </div>

                                <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>Kategori Listesi</CardTitle>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Resim</TableHead>
                                <TableHead>Başlık</TableHead>
                                <TableHead>Slug</TableHead>
                                <TableHead>Sıra</TableHead>
                                <TableHead>Durum</TableHead>
                                <TableHead className="text-right">İşlemler</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {sortedCategories.map((item) => (
                                <TableRow key={item.id}>
                                    <TableCell>
                                        {item.image ? (
                                            <img
                                                src={`${import.meta.env.VITE_API_BASE_URL}${item.image}`}
                                                alt={item.title}
                                                className="h-10 w-10 object-cover rounded"
                                            />
                                        ) : (
                                            <div className="h-10 w-10 bg-gray-200 rounded flex items-center justify-center text-xs">
                                                No Img
                                            </div>
                                        )}
                                    </TableCell>
                                    <TableCell className="font-medium">
                                        <div style={{ paddingLeft: `${item.level * 20}px` }} className="flex items-center">
                                            {item.level > 0 && <span className="text-muted-foreground mr-2">└─</span>}
                                            {item.title}
                                        </div>
                                        {item.parent && (
                                            <div className="text-xs text-muted-foreground hidden">
                                                (Üst: {item.parent.title})
                                            </div>
                                        )}
                                    </TableCell>
                                    <TableCell>{item.slug}</TableCell>
                                    <TableCell>{item.order}</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>
    )
}
