"use client"

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

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

interface ListSession {
    ocpp_transaction_id: string
    connector_number: number
}

export default function TriggerMessageModal({
    chargepoint_id, onClose, token,
} : ClearAuthModalProps) {
    const [session, setSession] = useState<ListSession[]>([]);
    const [selectedMessage, setSelectedMessage] = useState("");
    const [nozzle, setNozzle] = useState<number>(0);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        const loadTenant = async () => {
            try {
                const fd = new FormData();

                fd.append("charge_point_id", chargepoint_id);
                fd.append("token", token); 

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

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

                const result = await response.json();

                setSession(result.data ?? []);
            } catch (error) {
                console.error("Failed to load tiers:", error);
            } finally {
                setLoading(false);
            }
        };

        loadTenant();
    }, []);

    const handleGetDiagnostics = async () => {
        onClose();
        Swal.fire({
            title: "Processing Stop Transaction...",
            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("requested_message", selectedMessage); 
            fd.append("connector_id", String(nozzle)); 

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

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

            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">Trigger Message - {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>Request Message</p>
                                    <select name="session_id" className="form-select" value={selectedMessage} onChange={(e) => setSelectedMessage(e.target.value)}>
                                        <option value="">Choose Message</option>
                                        <option value="StatusNotification">Status Notification</option>
                                        <option value="MeterValues">Meter Values</option>
                                        <option value="Heartbeat">Heartbeat</option>
                                        <option value="BootNotification">Boot Notification</option>
                                        <option value="DiagnosticsStatusNotification">Diagnostics Status Notification</option>
                                        <option value="FirmwareStatusNotification">Firmware Status Notification</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="form-label">Connector / Nozzle Number</label>
                                    <input type="number" name="connector_id" className="form-control" onChange={(e) => setNozzle(Number(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" /> Triggering... </> 
                                ) : ( 
                                    <> <i className="ti ti-http-get me-1" /> Trigger Message </> 
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}