"use client"

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

interface ClearAuthModalProps {
    chargepoint_id: string;
    token: string;
    onClose: () => void;
}

interface ConfigurationResponse { 
    key: string
    readonly: boolean
    value: string
}

interface DataTableInstance { 
    destroy: () => void; 
}

export default function GerConfigurationModal({
    chargepoint_id, onClose, token,
} : ClearAuthModalProps) {
    const [configuaration, setConfiguration] = useState<ConfigurationResponse[]>([]);
    const [loading, setLoading] = useState(false);

    const tableRef = useRef<HTMLTableElement>(null);
    const dataTableRef = useRef<DataTableInstance | null>(null);

    const cleanupDataTable = () => { 
        if (dataTableRef.current) { 
            try { 
                dataTableRef.current.destroy(); 
            } catch (err) { 
                console.warn("DATATABLE DESTROY ERROR:", err); 
            } 
            dataTableRef.current = null; 
        } 
    };

    useEffect(() => {
        let cancelled = false;
        const loadChargerDetail = async () => {
            Swal.fire({
                title: "Processing Get List Configuration...",
                text: "Please wait",
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                },
            });
            try {
                setLoading(true);
                const fd = new FormData();
                fd.append("charge_point_id", chargepoint_id);
                fd.append("token", token); 

                const response = await fetch("/api/ocpp/configuration", {
                    method: "POST",
                    body: fd,
                });

                if (!response.ok) {
                    onClose();
                    Swal.fire({
                        icon: "error",
                        title: "Failed",
                        text: "Something went wrong",
                        allowOutsideClick: false,
                    });
                    return;
                }

                Swal.close();
                const result = await response.json();
                if (!result.result) {
                    onClose();
                    Swal.fire({
                        icon: "error",
                        title: "Failed",
                        text: result.msg || "Something went wrong",
                        allowOutsideClick: false,
                    });
                    return;
                }
                setConfiguration(result.data);
            } catch (err) {
                onClose();
                Swal.close();
                Swal.fire({
                    icon: "error",
                    title: "Failed",
                    text: "Something went wrong...",
                    allowOutsideClick: false,
                });
                return;;
            } finally {
                setLoading(false);
            }
        };

        loadChargerDetail();
        return () => { 
            cancelled = true; 
        };
    }, [chargepoint_id, token])

    useEffect(() => { 
        if (loading) { 
            return; 
        } 
        if (!tableRef.current) { 
            return; 
        } 
        if (configuaration.length === 0) { 
            cleanupDataTable(); 
            return; 
        } 
        let cancelled = false; 
        const initDataTable = async () => { 
            /** * Tunggu sampai React selesai melakukan DOM update. */ 
            await new Promise<void>((resolve) => { 
                requestAnimationFrame(() => resolve()); 
            }); 
            if (cancelled || !tableRef.current) { 
                return; 
            } 
            /** * Destroy instance sebelumnya. */ 
            cleanupDataTable(); 
            const { DataTable } = await import( "simple-datatables" ); 
            if (cancelled || !tableRef.current) { 
                return; 
            } 
            dataTableRef.current = new DataTable( 
                tableRef.current, { 
                    searchable: true, 
                    fixedHeight: false, 
                    perPage: 10, 
                    perPageSelect: [10, 20, 50], 
                    labels: { 
                        placeholder: "Search...", 
                        perPage: "{select} entries per page", 
                        noRows: "No configuration found", 
                        info: "Showing {start} to {end} of {rows} entries", 
                    }, 
                } 
            ); 
            console.log( "DataTable initialized:", configuaration.length ); 
        }; 
        initDataTable(); return () => { 
            cancelled = true; 
        }; 
    }, [loading, configuaration]); 
    
    /** * Destroy DataTable ketika modal/component unmount. */ 
    useEffect(() => { 
        return () => { 
            cleanupDataTable(); 
        }; 
    }, []);
    return (
        <>
            <div className="modal modal-blur modal-lg fade show d-block" tabIndex={-1} role="dialog" style={{ backgroundColor: "rgba(0, 0, 0, 0.4)" }}>
                <div className="modal-dialog modal-dialog-centered" role="document">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h5 className="modal-title">Get List Configuration Chargepoint - {chargepoint_id}</h5>
                            <button type="button" className="btn-close" onClick={onClose}></button>
                        </div>

                        <div className="modal-body">
                            <div className="table-responsive">
                                <table ref={tableRef} className="table card-table table-vcenter text-nowrap datatable" >
                                    <thead>
                                        <tr>
                                            <th>Key</th>
                                            <th>ReadOnly</th>
                                            <th>Value</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {configuaration.map((data, i) => (
                                        <tr key={i}>
                                            <td>{data.key}</td>
                                            <td>
                                                {data.readonly ? (
                                                    <span className="badge badge-outline text-green">Yes</span>
                                                ) : (
                                                    <span className="badge badge-outline text-red">No</span>
                                                )}
                                            </td>
                                            <td>{data.value}</td>
                                        </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <div className="modal-footer">
                            <button type="button" className="btn btn-danger btn-outline" onClick={onClose}>Cancel</button>
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}