"use client"

import { useState } from "react";
import Swal from "sweetalert2";

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

export default function ShowUpdateCertificateCSModal({
    chargepoint_id, onClose, token,
} : ClearAuthModalProps) {
    const [value, setValue] = useState("");
    const [selectedCertificateType, setSelectedCertificateType] = useState("");
    const [selectedCertificateMethod, setSelectedCertificateMethod] = useState("");
    const [loading, setLoading] = useState(false);

    const handleGetDiagnostics = async () => {
        onClose();
        Swal.fire({
            title: "Processing Updating 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("certificate_type", selectedCertificateType);
            fd.append("certificate_method", selectedCertificateMethod);
            if (selectedCertificateMethod === "manual") { 
                fd.append("certificate_data", value); 
            }

            const response = await fetch("/api/ocpp/chargepoint-certificate/update", {
                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,
            });
        }
    };

    const handleCertificateMethodChange = ( e: React.ChangeEvent<HTMLSelectElement> ) => { 
        const method = e.target.value; setSelectedCertificateMethod(method); 
        // Kalau Automatic, hapus certificate manual 
        if (method === "automatic") { 
            setValue(""); 
        } 
    };
    return (
        <>
            <div className="modal modal-blur 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" onSubmit={(e) => { e.preventDefault(); handleGetDiagnostics(); }}>
                                <div>
                                    <p>Certificate Type</p>
                                    <select name="certificate_type" className="form-select" value={selectedCertificateType} onChange={(e) => setSelectedCertificateType(e.target.value)}>
                                        <option value="">Choose Certificate</option>
                                        <option value="SignChargePointCertificate">Sign ChargePoint Certificate</option>
                                        <option value="ChargingStationCertificate">Charging Station Certificate</option>
                                        <option value="V2GCertificate">V2G Certificate</option>
                                    </select>
                                </div>
                                <div>
                                    <p>Certificate Method</p>
                                    <select name="certificate_method" className="form-select" value={selectedCertificateMethod} onChange={handleCertificateMethodChange} disabled={loading}>
                                        <option value="">Choose Method</option>
                                        <option value="manual">Manual</option>
                                        <option value="automatic">Automatic</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="form-label">Certificate</label>
                                    <textarea className="form-control" name="certificate_data" rows={6} 
                                    placeholder={
                                        selectedCertificateMethod === "manual" 
                                        ? "Paste certificate..." 
                                        : "Certificate is disabled for automatic method" 
                                    } 
                                    value={value}
                                    disabled={ loading || selectedCertificateMethod !== "manual" }
                                    onChange={(e) => setValue(e.target.value) }/>
                                </div>
                            </form>
                        </div>

                        <div className="modal-footer">
                            <button type="button" className="btn btn-danger btn-outline" onClick={onClose}>Cancel</button>
                            <button type="button" className="btn btn-success btn-outline" onClick={handleGetDiagnostics} disabled={loading}>
                                {loading ? ( 
                                    <><span className="spinner-border spinner-border-sm me-2" role="status" /> Updating Certificate... </> 
                                ) : ( 
                                    <> <i className="ti ti-http-get me-1" /> Update Certificate </> 
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}