"use client"

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

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

interface ListCertificate {
    hash_algorithm: string
    issuer_name_hash: string
    issuer_key_hash: string
    serial_number: string
}

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

export default function DeleteCertificateCPModal({
    chargepoint_id, onClose, token,
} : ClearAuthModalProps) {
    const [certificate, setCertificate] = useState<ListCertificate[]>([]);
    const [selectedCertificateType, setSelectedCertificateType] = useState("");
    const [loading, setLoading] = useState(false);

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

    const handleCertificateTypeChange = async ( e: React.ChangeEvent<HTMLSelectElement> ) => {
        const certificateType = e.target.value;
        setSelectedCertificateType(certificateType);

        if (!certificateType) {
            return;
        }

        try {
            setLoading(true);

            const fd = new FormData(); 
            
            fd.append("charge_point_id", chargepoint_id); 
            fd.append("token", token); 
            fd.append("certificate_type", certificateType);

            const response = await fetch("/api/ocpp/chargepoint-certificate/list", { 
                method: "POST", 
                body: fd, 
            }); 
            
            const result = await response.json(); 
            if (!response.ok || !result.result) { 
                Swal.fire({ 
                    icon: "error", 
                    title: "Failed", 
                    text: result.msg || "Failed to get certificate", 
                }); 
                return; 
            } 
            
            console.log("Certificate list:", result.data);
            setCertificate(result.data);
        } catch (err) { 
            console.log("Certificate list error:", err); 
            Swal.fire({ 
                icon: "error", 
                title: "Error", 
                text: "Something went wrong", 
            }); 
        } finally { 
            setLoading(false); 
        }
    }

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

    useEffect(() => { 
        if (loading) { 
            return; 
        } 
        if (!tableRef.current) { 
            return; 
        } 
        if (certificate.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:", certificate.length ); 
        }; 
        initDataTable(); return () => { 
            cancelled = true; 
        }; 
    }, [loading, certificate]); 
    
    /** * Destroy DataTable ketika modal/component unmount. */ 
    useEffect(() => { 
        return () => { 
            cleanupDataTable(); 
        }; 
    }, []);
    
    const handleDeleteCertificate = async (certificate: ListCertificate) => {
        onClose();
        Swal.fire({
            title: "Processing Installing Certificate...",
            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); 
            fd.append("hash_algorithm", certificate.hash_algorithm);
            fd.append("issuer_name_hash", certificate.issuer_name_hash); 
            fd.append("issuer_key_hash", certificate.issuer_key_hash); 
            fd.append("serial_number", certificate.serial_number); 

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

            if (!response.ok) {
                throw new Error("Failed to clear authorization");
            }

            Swal.close();
            const result = await response.json();

            if (!result.result) {
                Swal.fire({
                    icon: "error",
                    title: "Failed",
                    text: result.msg || "Something went wrong",
                    allowOutsideClick: false,
                });
                return;
            }
            Swal.fire({
                icon: "success",
                title: "Success!",
                text: result.data.status + " - " + result.msg,
                allowOutsideClick: false,
            });
        } catch (err) {
            Swal.close();
            Swal.fire({
                icon: "error",
                title: "Error",
                text: "Something went wrong",
                allowOutsideClick: false,
            });
        }
    };
    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">Update Chargepoint Password for Basic Auth - {chargepoint_id}</h5>
                            <button type="button" className="btn-close" onClick={onClose}></button>
                        </div>

                        <div className="modal-body">
                            <form className="space-y">
                                <div>
                                    <p>Certificate Type</p>
                                    <select name="certificate_type" className="form-select" value={selectedCertificateType} onChange={handleCertificateTypeChange} disabled={loading}>
                                        <option value="">Choose Certificate</option>
                                        <option value="ManufacturerRootCertificate">Manufacturer Root Certificate</option>
                                        <option value="CentralSystemRootCertificate">Central System Root Certificate</option>
                                    </select>
                                </div>
                            </form>
                            <div className="table-responsive mt-3">
                                <p>List Certificate</p>
                                <table ref={tableRef} className="table card-table table-vcenter text-nowrap datatable" >
                                    <thead>
                                        <tr>
                                            <th>Hash Algoritm</th>
                                            <th>Serial Number</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {certificate.map((data, i) => (
                                        <tr key={i}>
                                            <td>{data.hash_algorithm}</td>
                                            <td>{data.serial_number}</td>
                                            <td>
                                                <button className="btn btn-outline btn-danger btn-sm" onClick={() => handleDeleteCertificate(data)} disabled={loading}>
                                                    {loading ? ( 
                                                        <><span className="spinner-border spinner-border-sm me-2" role="status" /> Deleting... </> 
                                                    ) : ( 
                                                        <> <i className="ti ti-trash me-1" /> Delete </> 
                                                    )}
                                                </button>
                                            </td>
                                        </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}