"use client"

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import Swal from "sweetalert2";

interface AuditTrail {
    id: string;
    date: string;
    actor: string;
    action: string;
    tenant: string
    endpoint: string
    response: string
}

export default function AuditTrailTable() {
    const tableRef = useRef<HTMLTableElement>(null);
    const datatable = useRef<any>(null);
    const [modules, setUsers] = useState<AuditTrail[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        loadUsers();
        return () => {
            cleanupDataTable();
        };
    }, []);


    useEffect(() => {
        if (loading) return;
        if (!tableRef.current) return;

        async function initDataTable() {
            const { DataTable } = await import(
                "simple-datatables"
            );

            cleanupDataTable();
            datatable.current = new DataTable(
                tableRef.current!,
                {
                    searchable: true,
                    perPage: 10,
                    perPageSelect: [10, 20, 50, 100],
                }
            );
        }
        initDataTable();
    }, [loading]);

    function cleanupDataTable() {
        try {
            datatable.current?.destroy();
            datatable.current = null;

            document
                .querySelectorAll(".dataTable-wrapper")
                .forEach((el) => {
                    el.remove();
                });

        } catch (err) {
            console.error(
                "DATATABLE CLEANUP ERROR",
                err
            );
        }
    }

    useEffect(() => {
        const table = tableRef.current;
        if (!table) return;

        const handleClick = (event: MouseEvent) => {
            const target = event.target as HTMLElement;

            const button = target.closest("[data-live-event-id]") as HTMLButtonElement | null;
            if (!button) return;

            const id = button.dataset.liveEventId;
            if (!id) return;

            const item = modules.find((event) => event.id === id);
            if (!item) return;

            const row = button.closest("tr");
            if (!row) return;

            const nextRow = row.nextElementSibling;
            if (nextRow?.classList.contains("live-event-payload-row")) {
                nextRow.remove();
                return;
            }

            const detailRow =document.createElement("tr");
            detailRow.className = "live-event-payload-row";
            const td = document.createElement("td");
            td.colSpan = 5;
            td.innerHTML = `
                <div class="card bg-transparent border-0">
                    <div class="card-body">
                        <p>Endpoint : <span class="badge bg-teal-lt">${item.endpoint}</span></p>
                        <pre
                            class="mb-0"
                            style="
                                white-space: pre-wrap;
                                word-break: break-word;
                            "
                        ></pre>
                    </div>
                </div>
            `;
            const pre = td.querySelector("pre");
            if (pre) {
                pre.textContent = JSON.stringify(
                    item.response,
                    null,
                    2
                );
            }
            detailRow.appendChild(td);
            row.parentNode?.insertBefore(detailRow, row.nextSibling);
        };

        table.addEventListener("click", handleClick);

        return () => {
            table.removeEventListener("click", handleClick);
        };
    }, [modules]);

    async function loadUsers() {
        try {
            const res = await fetch("/api/audit", {
                    cache: "no-store"
                }
            );

            const data = await res.json();
            setUsers(data.data ?? []);
        } catch(err) {
            console.log("LOAD BANNED ERROR", err);
        } finally {
            setLoading(false);
        }
    }

    if (loading) {
        return <p>Loading...</p>;
    }

    
    return (
        <>
            <div className="card">
                <div className="card-header">
                    <h3 className="card-title">Audit Trail Logs</h3>
                </div>
                <div className="card-body border-bottom py-3">
                    <div className="table-responsive">
                        <table ref={tableRef} className="table table-selectable card-table table-vcenter text-nowrap datatable">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Actor</th>
                                    <th>Action</th>
                                    <th>Tenant</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                {modules.map((data, i) => (
                                    <tr key={data.id}>
                                        <td>{data.date}</td>
                                        <td>{data.actor}</td>
                                        <td>{data.action}</td>
                                        <td>{data.tenant}</td>
                                        <td>
                                            <button className="btn btn-outline btn-primary btn-sm" style={{ cursor: "pointer" }} data-live-event-id={data.id}> Detail</button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </>
    );
}