"use client";

import { useEffect, useRef, useState } from "react";

interface LiveEvent {
    id: string;
    direction: string;
    action: string;
    payload: unknown;
    latency: string;
    crated_at: string;
}

interface LiveEventTableWidgetProps {
    live_event: LiveEvent[];
}

export default function LiveEventTable({
    live_event,
}: LiveEventTableWidgetProps) {
    const containerRef = useRef<HTMLDivElement | null>(null);
    const dataTableRef = useRef<any>(null);

    const liveEventRef = useRef<LiveEvent[]>(live_event);

    const [selectedPayload, setSelectedPayload] =
        useState<LiveEvent | null>(null);

    /**
     * Keep latest live_event available for event delegation.
     */
    useEffect(() => {
        liveEventRef.current = live_event;
    }, [live_event]);

    /**
     * Initialize / rebuild DataTable whenever WS data changes.
     *
     * IMPORTANT:
     * React does NOT render the table itself.
     * simple-datatables owns the table DOM completely.
     */
    useEffect(() => {
        let cancelled = false;

        const initializeDataTable = async () => {
            const container = containerRef.current;

            if (!container) {
                return;
            }

            /**
             * Destroy previous DataTable.
             */
            if (dataTableRef.current) {
                try {
                    dataTableRef.current.destroy();
                } catch (error) {
                    console.warn(
                        "[DataTable] Failed to destroy:",
                        error
                    );
                }

                dataTableRef.current = null;
            }

            /**
             * Clear container.
             */
            container.innerHTML = "";

            if (!live_event || live_event.length === 0) {
                return;
            }

            /**
             * Wait until browser render cycle.
             */
            await new Promise<void>((resolve) => {
                requestAnimationFrame(() => {
                    resolve();
                });
            });

            if (cancelled) {
                return;
            }

            /**
             * Import DataTable only on client.
             */
            const { DataTable } =
                await import("simple-datatables");

            if (cancelled) {
                return;
            }

            /**
             * Create table manually.
             *
             * React does NOT manage this DOM.
             */
            const table = document.createElement("table");

            table.className =
                "table table-selectable card-table table-vcenter";

            /**
             * THEAD
             */
            const thead = document.createElement("thead");

            thead.innerHTML = `
                <tr>
                    <th>#</th>
                    <th>Date</th>
                    <th>Action</th>
                    <th>Latency</th>
                    <th>Action</th>
                </tr>
            `;

            /**
             * TBODY
             */
            const tbody = document.createElement("tbody");

            live_event.forEach((item) => {
                const tr = document.createElement("tr");

                /**
                 * Direction
                 */
                const directionTd =
                    document.createElement("td");

                if (item.direction === "inbound") {
                    directionTd.innerHTML = `
                        <div class="text-green">
                            <i class="ti ti-caret-down"></i>
                        </div>
                    `;
                } else {
                    directionTd.innerHTML = `
                        <div class="text-red">
                            <i class="ti ti-caret-up"></i>
                        </div>
                    `;
                }

                /**
                 * Date
                 */
                const dateTd =
                    document.createElement("td");

                dateTd.textContent =
                    item.crated_at || "-";

                /**
                 * Action
                 */
                const actionTd =
                    document.createElement("td");

                actionTd.textContent =
                    item.action || "-";

                /**
                 * Latency
                 */
                const latencyTd =
                    document.createElement("td");

                latencyTd.textContent =
                    item.latency || "-";

                /**
                 * Detail button
                 */
                const buttonTd =
                    document.createElement("td");

                const button =
                    document.createElement("button");

                button.type = "button";

                button.className =
                    "btn btn-outline-primary btn-sm";

                button.dataset.liveEventId = item.id;

                button.innerHTML = `
                    <i class="ti ti-eye me-1"></i>
                    Detail Payload
                `;

                buttonTd.appendChild(button);

                tr.appendChild(directionTd);
                tr.appendChild(dateTd);
                tr.appendChild(actionTd);
                tr.appendChild(latencyTd);
                tr.appendChild(buttonTd);

                tbody.appendChild(tr);
            });

            table.appendChild(thead);
            table.appendChild(tbody);

            /**
             * Add table to container.
             */
            container.appendChild(table);

            /**
             * Initialize simple-datatables.
             */
            try {
                const instance = new DataTable(table, {
                    searchable: true,
                    fixedHeight: false,
                    perPage: 10,
                    perPageSelect: [10, 20, 50],
                });

                dataTableRef.current = instance;

                console.log(
                    "[DataTable] Initialized:",
                    live_event.length,
                    "events"
                );
            } catch (error) {
                console.error(
                    "[DataTable] Initialization error:",
                    error
                );
            }
        };

        initializeDataTable();

        /**
         * Cleanup.
         */
        return () => {
            cancelled = true;

            if (dataTableRef.current) {
                try {
                    dataTableRef.current.destroy();
                } catch (error) {
                    console.warn(
                        "[DataTable] Cleanup error:",
                        error
                    );
                }

                dataTableRef.current = null;
            }
        };
    }, [live_event]);

    /**
     * Detail button event delegation.
     *
     * We attach the listener to the stable React container,
     * NOT directly to buttons generated by DataTable.
     */
    useEffect(() => {
        const container = containerRef.current;

        if (!container) {
            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 eventId =
                button.dataset.liveEventId;

            if (!eventId) {
                return;
            }

            const selected =
                liveEventRef.current.find(
                    (item) =>
                        item.id === eventId
                );

            if (!selected) {
                return;
            }

            setSelectedPayload(selected);
        };

        container.addEventListener(
            "click",
            handleClick
        );

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

    if (!live_event || live_event.length === 0) {
        return null;
    }

    return (
        <>
            <div className="card mt-3">
                <div className="card-header">
                    <h3 className="card-title">
                        <i className="ti ti-plug-connected me-2" />
                        Live Event Charger
                    </h3>
                </div>

                {/**
                 * IMPORTANT:
                 * Jangan taruh <table>, <thead>, <tbody>, dll
                 * di JSX React.
                 *
                 * simple-datatables akan menguasai seluruh
                 * DOM di dalam container ini.
                 */}
                <div
                    ref={containerRef}
                    className="table-responsive"
                />
            </div>

            {selectedPayload && (
                <PayloadModal
                    event={selectedPayload}
                    onClose={() =>
                        setSelectedPayload(null)
                    }
                />
            )}
        </>
    );
}

interface PayloadModalProps {
    event: LiveEvent;
    onClose: () => void;
}

function PayloadModal({
    event,
    onClose,
}: PayloadModalProps) {
    return (
        <div
            className="modal modal-blur fade show d-block"
            tabIndex={-1}
            role="dialog"
            aria-modal="true"
        >
            <div
                className="modal-backdrop show"
                onClick={onClose}
            />

            <div
                className="modal-dialog modal-xl modal-dialog-scrollable"
                role="document"
            >
                <div className="modal-content">
                    <div className="modal-header">
                        <h5 className="modal-title">
                            Live Event Payload
                        </h5>

                        <button
                            type="button"
                            className="btn-close"
                            aria-label="Close"
                            onClick={onClose}
                        />
                    </div>

                    <div className="modal-body">
                        <div className="row mb-3">
                            <div className="col-md-6">
                                <div className="text-secondary">
                                    Event ID
                                </div>

                                <div className="fw-bold">
                                    {event.id}
                                </div>
                            </div>

                            <div className="col-md-6">
                                <div className="text-secondary">
                                    Direction
                                </div>

                                <div className="fw-bold">
                                    {event.direction || "-"}
                                </div>
                            </div>
                        </div>

                        <div className="row mb-3">
                            <div className="col-md-6">
                                <div className="text-secondary">
                                    Action
                                </div>

                                <div className="fw-bold">
                                    {event.action || "-"}
                                </div>
                            </div>

                            <div className="col-md-6">
                                <div className="text-secondary">
                                    Latency
                                </div>

                                <div className="fw-bold">
                                    {event.latency || "-"}
                                </div>
                            </div>
                        </div>

                        <div>
                            <div className="text-secondary mb-2">
                                Payload
                            </div>

                            <pre
                                className="bg-dark-lt rounded p-3 mb-0"
                                style={{
                                    whiteSpace:
                                        "pre-wrap",
                                    wordBreak:
                                        "break-word",
                                    maxHeight: "600px",
                                    overflowY:
                                        "auto",
                                }}
                            >
                                {JSON.stringify(
                                    event.payload,
                                    null,
                                    2
                                )}
                            </pre>
                        </div>
                    </div>

                    <div className="modal-footer">
                        <button
                            type="button"
                            className="btn btn-secondary"
                            onClick={onClose}
                        >
                            Close
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}