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,
} 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, Trash2 } from "lucide-react"
import { useState } from "react"
import { useForm } from "react-hook-form"
import * as z from "zod"
import {
    deletePostComment,
    getPostComments,
    updatePostComment,
} from "@/features/blog/services/blog.service"
import type { PostComment } from "@/features/blog/types"

const formSchema = z.object({
    title: z.string().min(1, "Başlık zorunludur"),
    body: z.string().min(1, "Yorum zorunludur"),
    slug: z.string().optional(),
    is_active: z.boolean(),
    // parent_id can be handled if creating hierarchical view, but keeping simple for admin list
})

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

    // Admin endpoint fetches all comments if no post_id provided (or handle pagination server side eventually)
    // For now assuming getPostComments() without args fetches all or need specific admin endpoint
    const { data: comments, isLoading } = useQuery({
        queryKey: ["postComments"],
        queryFn: () => getPostComments(undefined, true),
    })

    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            title: "",
            body: "",
            slug: "",
            is_active: true,
        },
    })

    const updateMutation = useMutation({
        mutationFn: ({ id, data }: { id: string; data: z.infer<typeof formSchema> }) =>
            updatePostComment(id, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["postComments"] })
            toast({ title: "Başarılı", description: "Yorum 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: deletePostComment,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["postComments"] })
            toast({ title: "Başarılı", description: "Yorum 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 })
        }
    }

    const handleEdit = (item: PostComment) => {
        setEditingItem(item)
        form.reset({
            title: item.title,
            body: item.body,
            slug: item.slug,
            is_active: item.is_active,
        })
        setIsOpen(true)
    }

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

    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">Yorumlar</h2>
            </div>

            <Dialog open={isOpen} onOpenChange={setIsOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Yorumu Düzenle</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="Yorum Başlığı" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="body"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Yorum</FormLabel>
                                        <FormControl>
                                            <Textarea placeholder="İçerik" className="h-32" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="slug"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Slug</FormLabel>
                                        <FormControl>
                                            <Input placeholder="Slug" {...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">
                                Güncelle
                            </Button>
                        </form>
                    </Form>
                </DialogContent>
            </Dialog>

            <Card>
                <CardHeader>
                    <CardTitle>Yorum Listesi</CardTitle>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Yazar</TableHead>
                                <TableHead>Yorum</TableHead>
                                <TableHead>Yazı ID</TableHead>
                                <TableHead>Durum</TableHead>
                                <TableHead className="text-right">İşlemler</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {comments?.map((item) => (
                                <TableRow key={item.id}>
                                    <TableCell className="font-medium">
                                        {/* Assuming User object is loaded or IDs are shown */}
                                        <div className="text-xs text-muted-foreground">{item.user_id}</div>
                                        <div className="font-bold">{item.title}</div>
                                    </TableCell>
                                    <TableCell>
                                        <div className="truncate max-w-[300px]" title={item.body}>
                                            {item.body}
                                        </div>
                                    </TableCell>
                                    <TableCell className="text-xs">{item.post_id}</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>
    )
}
