"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import ShowAddNozzleModal from "@/components/modal/showAddNozzleModal"

interface DLMSitesData {
    id: string;
    name: string;
    max_power_kw: number;
    algorithm: string;
    active: boolean;
    nozzle: Nozzle[]
}

interface Nozzle {
    nozzle_id: string
    connector_number: number
    name: string
    status: string
    max_power_kw: number
    min_power_kw: number
    priority: number
    priority_weight: number
    active: boolean
}

interface TenantProps {
    tenant_id: string;
}

export default function ListSitesTable({
    tenant_id,
}: TenantProps) {
    const tableRef = useRef<HTMLTableElement>(null);
    const datatable = useRef<any>(null);
    const [showAddNozzleModal, setShowAddNozzleModal] = useState(false);

    const [sites, setSites] = useState<DLMSitesData[]>([]);
    const [loading, setLoading] = useState(true);

    const cleanupDataTable = useCallback(() => {
        try {
            if (datatable.current) {
                datatable.current.destroy();
                datatable.current = null;
            }
        } catch (err) {
            console.log("DATATABLE CLEANUP ERROR:", err);
        }
    }, []);

    const loadSites = useCallback(async () => {
        if (!tenant_id) {
            setSites([]);
            setLoading(false);
            return;
        }

        try {
            setLoading(true);

            const fd = new FormData();
            fd.append("tenant_id", tenant_id);

            const res = await fetch("/api/monitoring/charger/dlm/sites", {
                    method: "POST",
                    body: fd,
                    cache: "no-store",
                }
            );

            const data = await res.json();

            if (!res.ok) {
                throw new Error(data.message || data.msg || "Failed to load sites");
            }

            setSites(data.data ?? []);
        } catch (err) {
            console.log("LOAD DLM SITES ERROR:", err);

            setSites([]);
        } finally {
            setLoading(false);
        }
    }, [tenant_id]);

    useEffect(() => {
        loadSites();
    }, [loadSites]);

    useEffect(() => {
        if (loading) {
            return;
        }

        if (!tableRef.current) {
            return;
        }

        let mounted = true;

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

            if (!mounted || !tableRef.current) {
                return;
            }

            cleanupDataTable();

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

        initDataTable();

        return () => {
            mounted = false;
            cleanupDataTable();
        };
    }, [loading, sites, cleanupDataTable]);

    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 = sites.find((site) => site.id === id);
            if (!item) return;

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

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

            // Create detail row
            const detailRow = document.createElement("tr");
            detailRow.className = "live-event-payload-row";

            const td = document.createElement("td");
            td.colSpan = 5;

            /*
            * Create wrapper
            */
            const wrapper = document.createElement("div");
            wrapper.className = "card bg-transparent border-0";

            const cardBody = document.createElement("div");
            cardBody.className = "card-body";

            /*
            * Title
            */
            const title = document.createElement("h4");
            title.className = "mb-3";

            /*
            * Table
            */
            const tableElement = document.createElement("table");
            tableElement.className = "table table-vcenter card-table";

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

            const headerRow = document.createElement("tr");

            const headers = [
                "Name",
                "Connector",
                "Status",
                "Max Power kW",
                "Min Power kW",
            ];

            headers.forEach((header) => {
                const th = document.createElement("th");
                th.textContent = header;
                headerRow.appendChild(th);
            });

            thead.appendChild(headerRow);

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

            const nozzles = item.nozzle ?? [];
            if (nozzles.length === 0) {
                const emptyRow = document.createElement("tr");
                const emptyTd = document.createElement("td");

                emptyTd.colSpan = headers.length;
                emptyTd.className = "text-center text-muted";
                emptyTd.textContent = "No nozzle available";

                emptyRow.appendChild(emptyTd);

                tbody.appendChild(emptyRow);
            } else {
                item.nozzle.forEach((nozzle) => {
                    const nozzleRow = document.createElement("tr");

                    const name = document.createElement("td");
                    name.textContent = nozzle.name;

                    const connector = document.createElement("td");
                    connector.textContent = String(nozzle.connector_number);

                    const status = document.createElement("td");
                    const statusBadge = document.createElement("span");
                    statusBadge.className = nozzle.status === "available" ? "badge bg-green-lt" : "badge bg-secondary-lt";
                    statusBadge.textContent = nozzle.status;
                    status.appendChild(statusBadge);

                    const maxPower = document.createElement("td");
                    maxPower.textContent = String(nozzle.max_power_kw);

                    const minPower = document.createElement("td");
                    minPower.textContent = String(nozzle.min_power_kw);

                    nozzleRow.appendChild(name);
                    nozzleRow.appendChild(connector);
                    nozzleRow.appendChild(status);
                    nozzleRow.appendChild(maxPower);
                    nozzleRow.appendChild(minPower);

                    tbody.appendChild(nozzleRow);
                });
            }

            tableElement.appendChild(thead);
            tableElement.appendChild(tbody);

            cardBody.appendChild(title);
            cardBody.appendChild(tableElement);

            wrapper.appendChild(cardBody);

            td.appendChild(wrapper);

            detailRow.appendChild(td);

            row.parentNode?.insertBefore(detailRow, row.nextSibling);
        };

        table.addEventListener("click", handleClick);

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

    if (loading) {
        return (
            <div className="card">
                <div className="card-body text-center">
                    Loading...
                </div>
            </div>
        );
    }

    return (
        <div className="card">
            <div className="card-header">
                <h3 className="card-title">
                    List Sites
                </h3>
                <button className="btn btn-outline btn-primary ms-auto" onClick={() => setShowAddNozzleModal(true)}>Add Nozzle to Sites</button>
            </div>

            <div className="table-responsive">
                <table ref={tableRef} className="table table-selectable card-table table-vcenter text-nowrap">
                    <thead>
                        <tr>
                            <th>Site Name</th>
                            <th>Max Power kW</th>
                            <th>Algorithm</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        {sites.length > 0 ? (
                            sites.map((data) => (
                                <tr key={data.id}>
                                    <td>{data.name}</td>
                                    <td>{data.max_power_kw}</td>
                                    <td>{data.algorithm}</td>
                                    <td>
                                        {data.active ? (
                                            <span className="badge bg-green-lt">Active</span>
                                        ) : (
                                            <span className="badge bg-red-lt">Non Active</span>
                                        )}
                                    </td>
                                    <td>
                                        <button className="btn btn-outline btn-primary btn-sm" style={{ cursor: "pointer" }} data-live-event-id={data.id}> Detail</button> 
                                        <button className="btn btn-outline btn-success btn-sm" disabled={!data.nozzle || data.nozzle.length === 0}> Apply</button> 
                                        <button className="btn btn-outline btn-warning btn-sm" disabled={!data.nozzle || data.nozzle.length === 0}> Evaluate</button>
                                    </td>
                                </tr>
                            ))
                        ) : (
                            <tr>
                                <td colSpan={4} className="text-center">No sites found</td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>
            {showAddNozzleModal && (
                <ShowAddNozzleModal tenant_id={tenant_id} onClose={() => setShowAddNozzleModal(false)} />
            )}
        </div>
    );
}