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 {
    createPost,
    deletePost,
    getPostCategories,
    getPostTags,
    getPosts,
    updatePost,
    createPostCategoryQuick,
    createPostTagQuick,
} from "@/features/blog/services/blog.service"
import type { Post } from "@/features/blog/types"
import { Badge } from "@/components/ui/badge"
import { FancyMultiSelect } from "@/components/ui/fancy-multi-select"
import { Editor } from "@tinymce/tinymce-react"

const formSchema = z.object({
    title: z.string().min(1, "Başlık zorunludur"),
    content: z.string().optional(),
    keywords: z.string().min(1, "Anahtar kelimeler zorunludur"),
    video: z.string().optional(),
    is_active: z.boolean(),
    is_front: z.boolean(),
    category_ids: z.array(z.string()).optional(),
    tag_ids: z.array(z.string()).optional(),
})

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

    const { data: postsResponse, isLoading } = useQuery({
        queryKey: ["posts"],
        queryFn: () => getPosts({ admin: true }),
    })

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

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

    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            title: "",
            content: "",
            keywords: "",
            video: "",
            is_active: true,
            is_front: true,
            category_ids: [],
            tag_ids: [],
        },
    })

    const createMutation = useMutation({
        mutationFn: (formData: FormData) => createPost(formData),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["posts"] })
            toast({ title: "Başarılı", description: "Yazı 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 }) =>
            updatePost(id, formData),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["posts"] })
            toast({ title: "Başarılı", description: "Yazı 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: deletePost,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["posts"] })
            toast({ title: "Başarılı", description: "Yazı silindi" })
        },
        onError: (error: any) => {
            toast({
                title: "Hata",
                description: error.response?.data?.error || "Bir hata oluştu",
                variant: "destructive",
            })
        },
    })

    const createCategoryMutation = useMutation({
        mutationFn: createPostCategoryQuick,
        onSuccess: (newCategory) => {
            queryClient.invalidateQueries({ queryKey: ["postCategories"] })
            toast({ title: "Başarılı", description: "Kategori oluşturuldu" })
            // Auto-select the new category
            const currentIds = form.getValues("category_ids") || []
            form.setValue("category_ids", [...currentIds, newCategory.id])
        },
        onError: () => {
            toast({
                title: "Hata",
                description: "Kategori oluşturulamadı",
                variant: "destructive",
            })
        }
    })

    const createTagMutation = useMutation({
        mutationFn: createPostTagQuick,
        onSuccess: (newTag) => {
            queryClient.invalidateQueries({ queryKey: ["postTags"] })
            toast({ title: "Başarılı", description: "Etiket oluşturuldu" })
            // Auto-select the new tag
            const currentIds = form.getValues("tag_ids") || []
            form.setValue("tag_ids", [...currentIds, newTag.id])
        },
        onError: () => {
            toast({
                title: "Hata",
                description: "Etiket oluşturulamadı",
                variant: "destructive",
            })
        }
    })

    function onSubmit(values: z.infer<typeof formSchema>) {
        const formData = new FormData()
        formData.append("title", values.title)
        if (values.content) formData.append("content", values.content)
        formData.append("keywords", values.keywords)
        if (values.video) formData.append("video", values.video)
        formData.append("is_active", values.is_active.toString())
        formData.append("is_front", values.is_front.toString())

        if (values.category_ids) {
            values.category_ids.forEach((id) => formData.append("category_ids", id))
        }

        if (values.tag_ids) {
            values.tag_ids.forEach((id) => formData.append("tag_ids", id))
        }

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

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

    const handleEdit = (item: Post) => {
        setEditingItem(item)
        form.reset({
            title: item.title,
            content: item.content || "",
            keywords: item.keywords,
            video: item.video || "",
            is_active: item.is_active,
            is_front: item.is_front,
            category_ids: item.categories?.map((c) => c.id) || [],
            tag_ids: item.tags?.map((t) => t.id) || [],
        })
        setIsOpen(true)
    }

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

    const handleCreateOpen = () => {
        setEditingItem(null)
        form.reset({
            title: "",
            content: "",
            keywords: "",
            video: "",
            is_active: true,
            is_front: true,
            category_ids: [],
            tag_ids: [],
        })
        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">Yazılar</h2>
                <Dialog open={isOpen} onOpenChange={setIsOpen} modal={false}>
                    <DialogTrigger asChild>
                        <Button onClick={handleCreateOpen}>
                            <Plus className="mr-2 h-4 w-4" /> Yeni Yazı
                        </Button>
                    </DialogTrigger>
                    <DialogContent
                        className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto"
                        onInteractOutside={(e) => {
                            const target = e.target as Element;
                            if (target.closest(".tox-tinymce-aux") || target.closest(".moxman-window") || target.closest(".tox-dialog")) {
                                e.preventDefault();
                            }
                        }}
                    >
                        <DialogHeader>
                            <DialogTitle>
                                {editingItem ? "Yazıyı Düzenle" : "Yeni Yazı 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="Yazı Başlığı" {...field} />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="content"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>İçerik</FormLabel>
                                            <FormControl>
                                                <Editor
                                                    tinymceScriptSrc="/tinymce/tinymce.min.js"
                                                    licenseKey="gpl"
                                                    value={field.value}
                                                    onEditorChange={(content) => field.onChange(content)}
                                                    init={{
                                                        height: 500,
                                                        base_url: '/tinymce',
                                                        suffix: '.min',
                                                        menubar: false,
                                                        plugins: [
                                                            'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
                                                            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
                                                            'insertdatetime', 'media', 'table', 'code', 'help', 'wordcount'
                                                        ],
                                                        toolbar: 'undo redo | blocks | ' +
                                                            'bold italic forecolor | alignleft aligncenter ' +
                                                            'alignright alignjustify | bullist numlist outdent indent | ' +
                                                            'link image media | removeformat | help',
                                                        content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
                                                    }}
                                                />
                                            </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="video"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Video Embed Kodu (Opsiyonel)</FormLabel>
                                            <FormControl>
                                                <Input placeholder="iframe kodu" {...field} />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <div className="grid grid-cols-2 gap-4">
                                    <FormField
                                        control={form.control}
                                        name="category_ids"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>Kategoriler</FormLabel>
                                                <FormControl>
                                                    <FancyMultiSelect
                                                        options={
                                                            categories?.map((c) => ({
                                                                label: c.title,
                                                                value: c.id,
                                                            })) || []
                                                        }
                                                        selected={field.value || []}
                                                        onChange={field.onChange}
                                                        onCreate={(value) => createCategoryMutation.mutate(value)}
                                                        placeholder="Kategori Seçin"
                                                        emptyMessage="Kategori bulunamadı."
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="tag_ids"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>Etiketler</FormLabel>
                                                <FormControl>
                                                    <FancyMultiSelect
                                                        options={
                                                            tags?.map((t) => ({
                                                                label: t.tag,
                                                                value: t.id,
                                                            })) || []
                                                        }
                                                        selected={field.value || []}
                                                        onChange={field.onChange}
                                                        onCreate={(value) => createTagMutation.mutate(value)}
                                                        placeholder="Etiket Seçin"
                                                        emptyMessage="Etiket bulunamadı."
                                                    />
                                                </FormControl>
                                                <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>

                                <div className="flex space-x-4">
                                    <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>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="is_front"
                                        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>Ön Plan</FormLabel>
                                                </div>
                                            </FormItem>
                                        )}
                                    />
                                </div>

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

            <Card>
                <CardHeader>
                    <CardTitle>Yazı Listesi</CardTitle>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Resim</TableHead>
                                <TableHead>Başlık</TableHead>
                                <TableHead>Kategoriler</TableHead>
                                <TableHead>Durum</TableHead>
                                <TableHead className="text-right">İşlemler</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {postsResponse?.data?.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-16 object-cover rounded"
                                            />
                                        ) : (
                                            <div className="h-10 w-16 bg-gray-200 rounded flex items-center justify-center text-xs">
                                                No Img
                                            </div>
                                        )}
                                    </TableCell>
                                    <TableCell className="font-medium">
                                        <div className="truncate max-w-[200px]" title={item.title}>
                                            {item.title}
                                        </div>
                                    </TableCell>
                                    <TableCell>
                                        <div className="flex flex-wrap gap-1">
                                            {item.categories?.map((c) => (
                                                <Badge
                                                    key={c.id}
                                                    variant="secondary"
                                                    className="text-xs"
                                                >
                                                    {c.title}
                                                </Badge>
                                            ))}
                                        </div>
                                    </TableCell>
                                    <TableCell>
                                        <div className="flex flex-col gap-1">
                                            <span
                                                className={`px-2 py-0.5 rounded text-[10px] w-fit ${item.is_active
                                                    ? "bg-green-100 text-green-800"
                                                    : "bg-red-100 text-red-800"
                                                    }`}
                                            >
                                                {item.is_active ? "Aktif" : "Pasif"}
                                            </span>
                                            {item.is_front && (
                                                <span className="px-2 py-0.5 rounded text-[10px] bg-blue-100 text-blue-800 w-fit">
                                                    Ön Plan
                                                </span>
                                            )}
                                        </div>
                                    </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>
    )
}
