import React, { useEffect } from "react";
import { useForm } from "@inertiajs/react";
import AuthenticatedLayout from "@/layouts/authenticated-layout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { Head } from "@inertiajs/react";
import { CKEditor } from "ckeditor4-react"; // ✅ Import CKEditor langsung

import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";

const slugify = (text: string) => text.toLowerCase().replace(/\s+/g, "-");

interface Kategori {
    KategoriId: number;
    NamaKategori: string;
}

interface SubKategori {
    SubKategoriId: number;
    KategoriId: number;
    NamaSubKategori: string;
}

interface AddPostProps {
    kategori: Kategori[];
    subkategori: SubKategori[];
}

export default function AddPost({ kategori, subkategori }: AddPostProps) {
    const { toast } = useToast();
    const { data, setData, post, reset } = useForm({
        KategoriId: "",
        SubKategoriId: "",
        JudulPost: "",
        SlugPost: "",
        DescPost: "",
        ImagePost: null as File | null,
        IsPublish: false,
    });

    useEffect(() => {
        setData("SlugPost", slugify(data.JudulPost));
    }, [data.JudulPost]);

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        const formData = new FormData();
        formData.append("KategoriId", data.KategoriId);
        formData.append("SubKategoriId", data.SubKategoriId);
        formData.append("JudulPost", data.JudulPost);
        formData.append("SlugPost", data.SlugPost);
        formData.append("DescPost", data.DescPost);
        formData.append("IsPublish", data.IsPublish.toString());

        if (data.ImagePost) {
            formData.append("ImagePost", data.ImagePost);
        }

        post("/admin/post", {
            data: formData,
            headers: { "Content-Type": "multipart/form-data" },
            onSuccess: () => {
                toast({
                    title: "Berhasil",
                    description: "Post berhasil dibuat",
                    variant: "default",
                });
                reset();
            },
            onError: () => {
                toast({
                    title: "Gagal",
                    description: "Terjadi kesalahan saat membuat Post",
                    variant: "destructive",
                });
            },
        });
    };

    return (
        <AuthenticatedLayout header="Tambah Post">
            <Head title="Tambah Post" />
            <div className="container mx-auto p-4">
                <form onSubmit={handleSubmit} className="space-y-4">
                    <Input
                        type="text"
                        placeholder="Judul Post"
                        value={data.JudulPost}
                        onChange={(e) => setData("JudulPost", e.target.value)}
                    />
                    <Input
                        type="text"
                        placeholder="Slug Post"
                        value={data.SlugPost}
                        readOnly
                    />
                    <Select
                        onValueChange={(value) =>
                            setData("KategoriId", Number(value).toString())
                        }
                    >
                        <SelectTrigger>
                            <SelectValue placeholder="Pilih Kategori" />
                        </SelectTrigger>
                        <SelectContent>
                            {kategori.map((kat) => (
                                <SelectItem
                                    key={kat.KategoriId}
                                    value={kat.KategoriId.toString()}
                                >
                                    {kat.NamaKategori}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>

                    {data.KategoriId && (
                        <Select
                            onValueChange={(value) =>
                                setData(
                                    "SubKategoriId",
                                    Number(value).toString()
                                )
                            }
                        >
                            <SelectTrigger>
                                <SelectValue placeholder="Pilih SubKategori" />
                            </SelectTrigger>
                            <SelectContent>
                                {subkategori
                                    .filter(
                                        (sub) =>
                                            sub.KategoriId ===
                                            Number(data.KategoriId)
                                    )
                                    .map((sub) => (
                                        <SelectItem
                                            key={sub.SubKategoriId}
                                            value={sub.SubKategoriId.toString()}
                                        >
                                            {sub.NamaSubKategori}
                                        </SelectItem>
                                    ))}
                            </SelectContent>
                        </Select>
                    )}

                    <div className="relative min-h-[300px]">
                        <CKEditor
                            initData={data.DescPost}
                            onChange={(evt) => {
                                const newData = evt.editor.getData();
                                setData("DescPost", newData);
                            }}
                            config={{
                                height: 300,
                                removePlugins:
                                    "easyimage,cloudservices,exportpdf",
                                toolbar: [
                                    { name: "document", items: ["Source"] },
                                    {
                                        name: "clipboard",
                                        items: [
                                            "Cut",
                                            "Copy",
                                            "Paste",
                                            "PasteText",
                                            "PasteFromWord",
                                            "-",
                                            "Undo",
                                            "Redo",
                                        ],
                                    },
                                    {
                                        name: "editing",
                                        items: [
                                            "Find",
                                            "Replace",
                                            "-",
                                            "SelectAll",
                                        ],
                                    },
                                    {
                                        name: "basicstyles",
                                        items: [
                                            "Bold",
                                            "Italic",
                                            "Underline",
                                            "Strike",
                                            "Subscript",
                                            "Superscript",
                                            "-",
                                            "RemoveFormat",
                                        ],
                                    },
                                    {
                                        name: "paragraph",
                                        items: [
                                            "NumberedList",
                                            "BulletedList",
                                            "-",
                                            "Outdent",
                                            "Indent",
                                            "-",
                                            "Blockquote",
                                            "-",
                                            "JustifyLeft",
                                            "JustifyCenter",
                                            "JustifyRight",
                                            "JustifyBlock",
                                        ],
                                    },
                                    {
                                        name: "links",
                                        items: ["Link", "Unlink"],
                                    },
                                    {
                                        name: "insert",
                                        items: [
                                            "Image",
                                            "Table",
                                            "HorizontalRule",
                                            "SpecialChar",
                                        ],
                                    },
                                    {
                                        name: "styles",
                                        items: [
                                            "Styles",
                                            "Format",
                                            "Font",
                                            "FontSize",
                                        ],
                                    },
                                    {
                                        name: "colors",
                                        items: ["TextColor", "BGColor"],
                                    },
                                    { name: "tools", items: ["Maximize"] },
                                ],
                                filebrowserUploadUrl: "/images/posts",
                                filebrowserUploadMethod: "form",
                                removeButtons: "",
                            }}
                        />
                    </div>
                    <Input
                        type="file"
                        accept="image/png, image/jpg, image/webp"
                        onChange={(e) => {
                            if (e.target.files && e.target.files[0]) {
                                setData("ImagePost", e.target.files[0]);
                            }
                        }}
                    />

                    <Button type="submit" className="bg-blue-600 text-white">
                        Simpan
                    </Button>
                </form>
            </div>
        </AuthenticatedLayout>
    );
}
