"use client"

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

interface ListTenantProps {
    tenantId: string
}

interface Location {
    id: string
    name: string
}

export default function CreateSites({
    tenantId,
}: ListTenantProps) {
    const [location, setLocation] = useState<Location[]>([]);
    const [loading, setLoading] = useState(false);
    const [selectedLocation, setSelectedLocation] = useState("");
    const [code, setCode] = useState("");
    const [name, setName] = useState("");
    const [maxPowerKw, setMaxPowerkW] = useState(0);
    const [selectedAlgoritm, setSelectedAlgoritm] = useState("");
    const [selectedStatus, setSelectedStatus] = useState("");

    useEffect(() => {
        const loadLocation = async () => {
            try {
                const fd = new FormData();
                fd.append("tenant_id", tenantId);

                const res = await fetch("/api/monitoring/charger/dlm/location", {
                        method: "POST",
                        body: fd,
                        cache: "no-store",
                    }
                );

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

                const result = await res.json();
                setLocation(result.data)
            } catch (error) {
                console.error("Failed to load tiers:", error);
            } finally {
                setLoading(false);
            }
        };

        loadLocation();
    }, []);

    const handleSubmit = async () => {
        Swal.fire({
            title: "Processing Create Sites...",
            text: "Please wait",
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            },
        });
        try {
            setLoading(true);

            const fd = new FormData();

            fd.append("tenant_id", tenantId);
            fd.append("location_id", selectedLocation); 
            fd.append("code", code);  
            fd.append("name", name);  
            fd.append("max_power_kw", String(maxPowerKw));  
            fd.append("algorithm", selectedAlgoritm);  
            fd.append("active", selectedStatus);  

            const response = await fetch("/api/monitoring/charger/dlm/create", {
                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,
            })
            .then((result) => {
                if (result.isConfirmed) {
                    window.location.reload();
                }
            });
        } catch (err) {
            Swal.close();
            Swal.fire({
                icon: "error",
                title: "Error",
                text: "Something went wrong",
                allowOutsideClick: false,
            });
        }
    };
    return (
        <>
        <div className="card">
            <div className="card-header">
                <h3 className="card-title">
                    Create New Sites
                </h3>
            </div>
            <div className="card-body">
                <form className="space-y" onSubmit={handleSubmit}>
                    <div>
                        <label className="form-label">List Location</label>
                        <select name="location_id" className="form-select" value={selectedLocation} onChange={(e) => setSelectedLocation(e.target.value)}>
                            <option value="">{loading ? "Loading Location..." : "Choose Location"}</option>
                            {location.map((data) => (
                                <option key={data.id} value={data.id}>{data.name}</option>
                            ))}
                        </select>
                    </div>
                    <div>
                        <label className="form-label">Code</label>
                        <input type="text" name="start_date" className="form-control" onChange={(e) => setCode(e.target.value) }/>
                    </div>
                    <div>
                        <label className="form-label">Name</label>
                        <input type="text" name="start_date" className="form-control" onChange={(e) => setName(e.target.value) }/>
                    </div>
                    <div>
                        <label className="form-label">Max Power kW</label>
                        <input type="number" name="start_date" className="form-control" onChange={(e) => setMaxPowerkW(Number(e.target.value)) }/>
                    </div>
                    <div className="row">
                        <div className="col-6">
                            <label className="form-label">Algoritm</label>
                            <select name="location_id" className="form-select" value={selectedAlgoritm} onChange={(e) => setSelectedAlgoritm(e.target.value)}>
                                <option value="">Choose Algoritm</option>
                                <option value="weighted_priority">Weighted Priority</option>
                                <option value="equal_share">Equal Share</option>
                            </select>
                        </div>
                        <div className="col-6">
                            <label className="form-label">Status</label>
                            <select name="location_id" className="form-select" value={selectedStatus} onChange={(e) => setSelectedStatus(e.target.value)}>
                                <option value="">Choose Status</option>
                                <option value="true">Active</option>
                                <option value="false">No Active</option>
                            </select>
                        </div>
                    </div>
                    
                    <div>
                        <button type="submit" className="btn btn-outline btn-success w-100 d-flex align-items-center">
                            {loading ? ( 
                                <><span className="spinner-border spinner-border-sm me-2" role="status" /> Creating Site... </> 
                            ) : ( 
                                <> <i className="ti ti-device-floppy me-1" /> Create Site </> 
                            )}
                        </button>
                    </div>
                </form>
            </div>
        </div>
        </>
    )
}