"use client"

import { useEffect, useState } from "react"
import { apiFetch } from "./../lib/api"

export default function Permissions() {
    const [project, setProject] = useState("")
    const [sites, setSites] = useState<string[]>([])
    const [loading, setLoading] = useState(false)

    useEffect(() => {
        const fetchSites = async () => {
            try {
                const [resPrd, resDev] = await Promise.all([
                    apiFetch("/sites/prd").then(r => r.json()),
                    apiFetch("/sites/dev").then(r => r.json())
                ]);

                const prdList = resPrd.sites || [];
                const devList = resDev.sites || [];
                
                const allSites = [...prdList, ...devList];
                const cleanSites = [...new Set(allSites.map((s: string) => s.replace(/-le-ssl$/, '')))] as string[];
                
                setSites(cleanSites.sort());
            } catch (err) {
                console.error('API error:', err);
            }
        };
        fetchSites();
    }, [])

    async function handleAction(action: 'enable' | 'disable') {
        if (!project) return;
        setLoading(true);
        
        console.log(`[Front Log] Iniciando petición: /permissions/${action} para el proyecto: ${project}`);
        
        try {
            const response = await apiFetch(`/permissions/${action}`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ project })
            });

            console.log(`[Front Log] Status de la respuesta:`, response.status, response.statusText);

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                console.error(`[Front Log] Error devuelto por el servidor:`, errorData);
                throw new Error("Server disconnected or returned an error status");
            }

            alert(`Permissions ${action}d for ${project}`);
        } catch (err) {
            console.error('[Front Log] Error detectado en el bloque catch:', err);
            alert("Error updating permissions");
        } finally {
            setLoading(false);
        }
    }

    return (
        <div className="bg-white p-6 rounded-xl shadow-lg border border-gray-100 max-w-2xl mx-auto">
            <h2 className="text-xl font-bold text-gray-900 mb-6">Permissions Management</h2>

            <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-1">Seleccionar Sitio (PRD o DEV)</label>
                <select 
                    value={project}
                    onChange={e => setProject(e.target.value)}
                    className="w-full p-2.5 border border-gray-200 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                    <option value="">Seleccionar un sitio...</option>
                    {sites.map(p => (
                        <option key={p} value={p}>{p}</option>
                    ))}
                </select>
            </div>

            <div className="flex gap-4">
                <button 
                    onClick={() => handleAction('enable')}
                    disabled={loading || !project}
                    className="bg-green-600 text-white px-4 py-2 rounded font-semibold hover:bg-green-700 transition-colors cursor-pointer disabled:bg-gray-400"
                >
                    {loading ? "..." : "Enable"}
                </button>
                <button 
                    onClick={() => handleAction('disable')}
                    disabled={loading || !project}
                    className="bg-red-600 text-white px-4 py-2 rounded font-semibold hover:bg-red-700 transition-colors cursor-pointer disabled:bg-gray-400"
                >
                    {loading ? "..." : "Disable"}
                </button>
            </div>
        </div>
    )
}