/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";
import React, { useState, useEffect } from "react";  // ✅ added useEffect
import { useQuery } from "@tanstack/react-query";
// ✅ REMOVED: import DOMPurify from "isomorphic-dompurify";

import { ColumnDef } from "@tanstack/react-table";
import { Checkbox } from "@radix-ui/react-checkbox";
import { DotsHorizontalIcon } from "@radix-ui/react-icons";
import DataTable from "@/components/Table";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import Link from "next/link";
import { ErrorMessage } from "@/components/ui/error-message";
import Loading from "../../components/loading";
import { NewsCommentProps, NewsLikeProps, NewsProps } from "@/lib/features/admin/news/type";
import { geOneNews } from "@/lib/features/admin/news/service";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { CircleXIcon, Eye } from "lucide-react";

interface Props {
    dataId: number;
}

export const ViewNewsDialog = ({ dataId }: Props) => {

    const { data, isLoading, error } = useQuery({
        queryKey: ["view-news-details"],
        queryFn: () => geOneNews(dataId),
    });

    // view comment states
    const [selectedId, setSelectedId] = useState<number | null>(null);
    const [isViewModalOpen, setViewModalOpen] = useState(false);

    // ✅ sanitized description state — starts empty (safe for SSR)
    const [sanitizedDescription, setSanitizedDescription] = useState('');

    const openViewModal = (id: number) => {
        setSelectedId(id);
        setViewModalOpen(true);
    };

    const closeViewModal = () => {
        setViewModalOpen(false);
        setSelectedId(null);
    };

    console.log(selectedId, isViewModalOpen, closeViewModal);

    // ✅ sanitize only in the browser, after data loads
    useEffect(() => {
        const description = data?.data?.details?.description;
        if (!description) return;

        import('dompurify').then(({ default: DOMPurify }) => {
            setSanitizedDescription(
                DOMPurify.sanitize(description, {
                    ADD_TAGS: ["figure", "figcaption", "iframe", "oembed"],
                    ADD_ATTR: ["class", "style", "src", "alt", "href", "target", "rel", "allowfullscreen"],
                })
            );
        });
    }, [data?.data?.details?.description]);

    if (isLoading) return <Loading />;
    if (error) return <ErrorMessage error={error} fallback="Dashboard error" />;

    const detail: NewsProps = data?.data?.details || null;
    const comments: NewsCommentProps[] = data?.data?.details?.comments || [];
    const likes: NewsLikeProps[] = data?.data?.details?.liked || [];

    // comment columns
    const commentColumns: ColumnDef<NewsCommentProps>[] = [
        {
            id: "select",
            header: ({ table }) => (
                <Checkbox
                    checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
                    onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
                    aria-label="Select all"
                />
            ),
            cell: ({ row }) => (
                <Checkbox
                    checked={row.getIsSelected()}
                    onCheckedChange={(value) => row.toggleSelected(!!value)}
                    aria-label="Select row"
                />
            ),
            enableSorting: false,
            enableHiding: false,
        },
        {
            accessorKey: "tbl_userFname",
            header: () => <div className="text-left table-size">Name</div>,
            cell: ({ row }) => (
                <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
                    {row.getValue("tbl_userFname") + " " + row?.original?.tbl_userLname}
                </div>
            ),
        },
        {
            accessorKey: "description",
            header: () => <div className="text-left table-size">Comment</div>,
            cell: ({ row }) => (
                <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
                    <b>{row.getValue("description")}</b>
                </div>
            ),
        },
        {
            accessorKey: "date",
            header: () => <div className="text-left table-size">Date</div>,
            cell: ({ row }) => (
                <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
                    <b className="text-blue-500">{row.getValue("date") + "/" + row?.original?.hour}</b>
                </div>
            ),
        },
        {
            id: "actions",
            enableHiding: false,
            header: "Actions",
            cell: ({ row }) => (
                <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Button variant="ghost" className="h-8 w-8 p-0">
                            <span className="sr-only">Open menu</span>
                            <DotsHorizontalIcon className="h-4 w-4" />
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                        <DropdownMenuSeparator />
                        <DropdownMenuItem onClick={() => openViewModal(row?.original?.id)}>
                            <Eye /> View
                        </DropdownMenuItem>
                        <DropdownMenuItem>
                            <CircleXIcon className="text-red-500" /> Remove
                        </DropdownMenuItem>
                    </DropdownMenuContent>
                </DropdownMenu>
            ),
        },
    ];

    // like columns
    const likeColumns: ColumnDef<NewsLikeProps>[] = [
        {
            id: "select",
            header: ({ table }) => (
                <Checkbox
                    checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
                    onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
                    aria-label="Select all"
                />
            ),
            cell: ({ row }) => (
                <Checkbox
                    checked={row.getIsSelected()}
                    onCheckedChange={(value) => row.toggleSelected(!!value)}
                    aria-label="Select row"
                />
            ),
            enableSorting: false,
            enableHiding: false,
        },
        {
            accessorKey: "tbl_userFname",
            header: () => <div className="text-left table-size">Name</div>,
            cell: ({ row }) => (
                <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
                    {row.getValue("tbl_userFname") + " " + row?.original?.tbl_userLname}
                </div>
            ),
        },
        {
            accessorKey: "date",
            header: () => <div className="text-left table-size">Date</div>,
            cell: ({ row }) => (
                <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
                    <b className="text-blue-500">{row.getValue("date")}</b>
                </div>
            ),
        },
        {
            id: "actions",
            enableHiding: false,
            header: "Actions",
            cell: ({ row }) => (
                <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Button variant="ghost" className="h-8 w-8 p-0">
                            <span className="sr-only">Open menu</span>
                            <DotsHorizontalIcon className="h-4 w-4" />
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                        <DropdownMenuSeparator />
                        <DropdownMenuItem onClick={() => openViewModal(row?.original?.id)}>
                            <Eye /> View
                        </DropdownMenuItem>
                        <DropdownMenuItem>
                            <CircleXIcon className="text-red-500" /> Remove
                        </DropdownMenuItem>
                    </DropdownMenuContent>
                </DropdownMenu>
            ),
        },
    ];

    return (
        <div className="h-auto max-h-[80vh] overflow-y-auto scrollbar-hide">
            <div className="overflow-x-auto w-full grid grid-cols-1 gap-4">

                <fieldset className="pl-2 text-sm font-bold border-4 rounded-[10px] text-neutral-600 pb-4">
                    <legend className="text-blue-700 text-center">News information</legend>
                    <table className="min-w-full viewDetail">
                        <tbody className="w-full">
                            <tr style={{ border: 10 }} className="hover:bg-gray-50 border-2">
                                <td><b>Photo:</b></td>
                            </tr>
                            <tr style={{ border: 10 }} className="hover:bg-gray-50 border-2">
                                <td>
                                    <Image src={`${detail?.image}`} alt={detail?.title} width={200} height={200} />
                                </td>
                            </tr>
                            <tr style={{ border: 10 }} className="hover:bg-gray-50 border-2">
                                <td>
                                    <b>Title:</b>
                                    <Link href="#">{" " + detail?.title}</Link>
                                </td>
                            </tr>
                            <tr style={{ border: 10 }} className="hover:bg-gray-50 border-2">
                                <td><b>Subtitle:</b><b>{" " + detail?.subtitle}</b></td>
                            </tr>
                            <tr style={{ border: 10 }} className="hover:bg-gray-50 border-2">
                                <td><b>Likes:</b><b className="text-blue-800">{" " + detail?.likes}</b></td>
                            </tr>
                            <tr style={{ border: 10 }} className="hover:bg-gray-50 border-2">
                                <td className="py-2">
                                    <b>Description:</b>
                                    {/* ✅ sanitizedDescription is '' on server, populated on client */}
                                    <div
                                        className="ck-content font-normal mt-1 prose max-w-none"
                                        dangerouslySetInnerHTML={{ __html: sanitizedDescription }}
                                    />
                                </td>
                            </tr>
                            <tr style={{ border: 10 }} className="hover:bg-gray-50 border-2">
                                <td>
                                    <b>Create date:</b>
                                    <Link href="#">{" " + detail?.date}</Link>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </fieldset>

                <fieldset className="pl-2 text-sm font-bold border-4 rounded-[10px] text-neutral-600 pb-4">
                    <legend className="text-blue-700 text-center">Comments</legend>
                    <DataTable size={16} columns={commentColumns} data={comments} />
                </fieldset>

                <fieldset className="pl-2 text-sm font-bold border-4 rounded-[10px] text-neutral-600 pb-4">
                    <legend className="text-blue-700 text-center">Likes</legend>
                    <DataTable size={16} columns={likeColumns} data={likes} />
                </fieldset>

            </div>
        </div>
    );
};