"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 RemoteTransactionStopModal({
    chargepoint_id, onClose, token,
} : ClearAuthModalProps) {
    const [session, setSession] = useState<ListSession[]>([]);
    const [selectedSession, setSelectedSession] = 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("ocpp_transaction_id", selectedSession); 

            const response = await fetch("/api/ocpp/remote/stop", {
                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">Remote Stop Transaction - {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>List Tenant / CPO</p>
                                    <select name="session_id" className="form-select" value={selectedSession} onChange={(e) => setSelectedSession(e.target.value)}>
                                        <option value="">{loading ? "Loading Session..." : "Choose Session"}</option>
                                        {session.map((sess, i) => (
                                            <option key={i+1} value={sess.ocpp_transaction_id}>
                                                Nozzle No. {sess.connector_number} - {sess.ocpp_transaction_id}
                                            </option>
                                        ))}
                                    </select>
                                </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" /> Stopping Transaction... </> 
                                ) : ( 
                                    <> <i className="ti ti-http-get me-1" /> Stop Transaction </> 
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}