"use client"

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

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

export default function SendLocalVersionModal({
    chargepoint_id, onClose, token,
} : ClearAuthModalProps) {
    const [updateType, setUpdateType] = useState("Full");
    const [status, setStatus] = useState("DiagnosticsLog");
    const [idTag, setIdTag] = useState(""); 
    const [listVersion, setListVersion] = useState(""); 
    const [loading, setLoading] = useState(false);

    const handleGetDiagnostics = async () => {
        onClose();
        Swal.fire({
            title: "Processing Sending Local Version...",
            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("update_type", updateType); 
            fd.append("status", status); 
            fd.append("id_tag", idTag); 
            fd.append("list_version", listVersion); 

            const response = await fetch("/api/ocpp/version/send", {
                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 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">Send Local Version - {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 className="row">
                                    <div className="col-6">
                                        <label className="form-label">Update Version Type</label>
                                        <select name="update_type" className="form-select" value={updateType} onChange={(e) => setUpdateType(e.target.value) }>
                                            <option value="Full">Full</option>
                                            <option value="Differential">Differential</option>
                                        </select>
                                    </div>
                                    <div className="col-6">
                                        <label className="form-label">Status Version</label>
                                        <select name="status" className="form-select" value={status} onChange={(e) => setStatus(e.target.value) }>
                                            <option value="Accepted">Accepted</option>
                                            <option value="Rejected">Rejected</option>
                                        </select>
                                    </div>
                                </div>
                                <div className="row">
                                    <div className="col-6">
                                        <label className="form-label">ID Tag</label>
                                        <input type="text" name="id_tag" className="form-control" onChange={(e) => setIdTag(e.target.value) }/>
                                    </div>
                                    <div className="col-6">
                                        <label className="form-label">Version</label>
                                        <input type="number" name="list_version" className="form-control" onChange={(e) => setListVersion(e.target.value) }/>
                                    </div>
                                </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" /> Sending Local Version... </> 
                                ) : ( 
                                    <> <i className="ti ti-http-get me-1" /> Send Now </> 
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}