const { useState, useRef, useEffect } = React;

window.AdminAjustes = function({ 
    isMaster, 
    companyLogoUrl, 
    setCompanyLogoUrl, 
    showCompanyLogo, 
    setShowCompanyLogo, 
    inssRate, 
    setInssRate, 
    vacRate, 
    setVacRate, 
    lunchLimitMinutes, 
    setLunchLimitMinutes, 
    gracePeriodMinutes, 
    setGracePeriodMinutes, 
    maxTardinessAllowed, 
    setMaxTardinessAllowed, 
    tardinessPenaltyAction, 
    setTardinessPenaltyAction, 
    saveCompanySettings, 
    newReasonInput, 
    setNewReasonInput, 
    setReasonsList, 
    reasonsList 
}) {
    // ESTADOS ORIGINALES DE RECORTE DE LOGO
    const [showCropModal, setShowCropModal] = useState(false);
    const [rawImageSrc, setRawImageSrc] = useState(null);
    const [zoomScale, setZoomScale] = useState(1);
    const [panOffset, setPanOffset] = useState({ x: 0, y: 0 });
    const [isDragging, setIsDragging] = useState(false);
    const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
    const [isSavingLogo, setIsSavingLogo] = useState(false);

    // ESTADOS DE IA (GOOGLE GEMINI API)
    const [geminiApiKey, setGeminiApiKey] = useState('');
    const [showKey, setShowKey] = useState(false);
    const [testingAi, setTestingAi] = useState(false);
    const [aiStatusMsg, setAiStatusMsg] = useState('');

    const canvasRef = useRef(null);
    const imageObjRef = useRef(null);

    // Cargar la API Key guardada en la base de datos al montar el componente
    useEffect(() => {
        const loadSavedSettings = async () => {
            try {
                const res = await window.apiCall('get_initial_data', {});
                if (res && res.success && res.data && res.data.settings) {
                    if (res.data.settings.geminiApiKey) {
                        setGeminiApiKey(res.data.settings.geminiApiKey);
                    }
                }
            } catch (e) {}
        };
        loadSavedSettings();
    }, []);

    const handleFileSelect = (e) => {
        const file = e.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = (ev) => {
            const img = new Image();
            img.onload = () => {
                imageObjRef.current = img;
                setRawImageSrc(ev.target.result);
                setZoomScale(1);
                setPanOffset({ x: 0, y: 0 });
                setShowCropModal(true);
            };
            img.src = ev.target.result;
        };
        reader.readAsDataURL(file);
    };

    const drawCanvas = () => {
        const canvas = canvasRef.current;
        const img = imageObjRef.current;
        if (!canvas || !img) return;

        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        ctx.save();
        ctx.translate(canvas.width / 2 + panOffset.x, canvas.height / 2 + panOffset.y);
        ctx.scale(zoomScale, zoomScale);

        const hRatio = (canvas.width * 0.85) / img.width;
        const vRatio = (canvas.height * 0.85) / img.height;
        const ratio = Math.min(hRatio, vRatio);

        const drawW = img.width * ratio;
        const drawH = img.height * ratio;

        ctx.drawImage(img, -drawW / 2, -drawH / 2, drawW, drawH);
        ctx.restore();
    };

    useEffect(() => {
        if (showCropModal) {
            drawCanvas();
        }
    }, [showCropModal, zoomScale, panOffset]);

    const handleMouseDown = (e) => {
        setIsDragging(true);
        setDragStart({ x: e.clientX - panOffset.x, y: e.clientY - panOffset.y });
    };

    const handleMouseMove = (e) => {
        if (!isDragging) return;
        setPanOffset({
            x: e.clientX - dragStart.x,
            y: e.clientY - dragStart.y
        });
    };

    const handleMouseUp = () => setIsDragging(false);

    const handleApplyCropAndSave = async () => {
        const canvas = canvasRef.current;
        if (!canvas) return;

        setIsSavingLogo(true);
        const croppedBase64 = canvas.toDataURL('image/png', 0.95);

        try {
            const res = await window.apiCall('upload_company_logo', { logo_base64: croppedBase64 });

            if (res && res.success) {
                const finalUrl = res.logo_url;
                setCompanyLogoUrl(finalUrl);
                if (window.SHIFT_CONFIG) {
                    window.SHIFT_CONFIG.companyLogo = finalUrl;
                }
                setShowCropModal(false);
            } else {
                alert("Error del servidor: " + (res.error || "No se pudo guardar el logo"));
            }
        } catch (err) {
            console.error("Error al subir logo:", err);
        } finally {
            setIsSavingLogo(false);
        }
    };

    // Alternar visibilidad del logo y guardar inmediatamente en base de datos
    const handleToggleShowLogo = async (e) => {
        const newValue = e.target.checked;
        setShowCompanyLogo(newValue);
        await saveCompanySettings({ show_company_logo: newValue ? 1 : 0 });
    };

    // Probar conexión directa con Google Gemini
    const handleTestGeminiKey = async () => {
        if (!geminiApiKey.trim()) return alert("Ingresa primero una API Key de Google Gemini.");
        setTestingAi(true);
        setAiStatusMsg('');
        try {
            const res = await window.apiCall('ask_ai_copilot', {
                prompt: "Hola, responde brevemente con un saludo confirmando que la conexión está activa.",
                customApiKey: geminiApiKey.trim()
            });
            if (res && res.success && res.response) {
                setAiStatusMsg("✅ Conexión con Gemini exitosa");
            } else {
                setAiStatusMsg("❌ " + (res?.error || "Error al conectar con la API de Gemini"));
            }
        } catch (err) {
            setAiStatusMsg("❌ Error: " + err.message);
        } finally {
            setTestingAi(false);
        }
    };

    // Guardado general de todos los ajustes (incluye la API Key)
    const handleSaveAllSettings = async () => {
        await saveCompanySettings({
            gemini_api_key: geminiApiKey.trim()
        });
    };

    return (
        <div className="space-y-8 fade-in max-w-5xl pb-16">
            {/* SECCIÓN IA: GOOGLE GEMINI API */}
            <div className="bg-gradient-to-r from-slate-900 via-indigo-950 to-slate-900 p-8 rounded-[3rem] shadow-xl text-white space-y-5 border border-indigo-500/20 relative overflow-hidden">
                <div className="flex items-center gap-3.5">
                    <div className="w-12 h-12 rounded-2xl bg-indigo-600 flex items-center justify-center shadow-lg border border-indigo-400/30">
                        <svg className="w-6 h-6 text-white animate-pulse" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                        </svg>
                    </div>
                    <div>
                        <h3 className="text-lg font-black text-white flex items-center gap-2">
                            Google Gemini API (Shift Copilot AI)
                            <span className="px-2 py-0.5 bg-indigo-500/30 text-indigo-300 border border-indigo-400/30 rounded-full text-[8px] font-black uppercase">Motor IA</span>
                        </h3>
                        <p className="text-xs text-indigo-200 font-medium mt-0.5">
                            Permite al asistente realizar análisis automáticos de almuerzos, tardanzas, contratos y nómina.
                        </p>
                    </div>
                </div>

                <div className="space-y-2">
                    <label className="text-[10px] font-black uppercase tracking-widest text-indigo-300 block">
                        API Key de Google Gemini (gemini-1.5-flash / gemini-2.5-flash)
                    </label>
                    <div className="flex flex-col sm:flex-row gap-2">
                        <div className="relative flex-1">
                            <input 
                                type={showKey ? "text" : "password"} 
                                value={geminiApiKey} 
                                onChange={e => setGeminiApiKey(e.target.value)} 
                                placeholder="Pega tu API Key: AIzaSy..." 
                                className="w-full p-4 bg-white/10 border border-white/20 rounded-2xl text-xs font-mono font-bold text-white outline-none focus:border-indigo-400 placeholder:text-slate-400" 
                            />
                            <button 
                                type="button" 
                                onClick={() => setShowKey(!showKey)} 
                                className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white text-[10px] font-black uppercase"
                            >
                                {showKey ? "Ocultar" : "Mostrar"}
                            </button>
                        </div>
                        <button 
                            type="button" 
                            onClick={handleTestGeminiKey} 
                            disabled={testingAi || !geminiApiKey.trim()}
                            className="px-6 py-4 bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest shadow-md active:scale-95 transition-all whitespace-nowrap"
                        >
                            {testingAi ? "Probando..." : "Probar Conexión"}
                        </button>
                    </div>
                    {aiStatusMsg && (
                        <p className="text-xs font-bold mt-1 text-indigo-200">{aiStatusMsg}</p>
                    )}
                    <p className="text-[10px] text-slate-400 mt-1">
                        Puedes generar tu API Key gratuita en <a href="https://aistudio.google.com/" target="_blank" rel="noopener noreferrer" className="text-indigo-400 underline font-bold">Google AI Studio</a>.
                    </p>
                </div>
            </div>

            {/* SECCIÓN 1: IDENTIDAD CORPORATIVA */}
            <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 space-y-6">
                <div className="flex justify-between items-start">
                    <div>
                        <h2 className="text-xl font-black text-slate-900">Identidad Corporativa</h2>
                        <p className="text-slate-400 font-bold uppercase text-[10px] tracking-widest mt-0.5">
                            Logo oficial de la empresa visible en la App del personal y reportes
                        </p>
                    </div>
                    <label className="flex items-center gap-2 cursor-pointer bg-slate-50 hover:bg-slate-100 px-4 py-2 rounded-2xl border transition-colors">
                        <input 
                            type="checkbox" 
                            checked={Boolean(showCompanyLogo)} 
                            onChange={handleToggleShowLogo} 
                            className="w-4 h-4 accent-indigo-600 rounded cursor-pointer" 
                        />
                        <span className="text-xs font-black uppercase text-slate-700">Mostrar Logo en App</span>
                    </label>
                </div>

                <div className="grid md:grid-cols-2 gap-6 items-center p-6 bg-slate-50 rounded-3xl border">
                    <div className="space-y-3">
                        <label className="text-[10px] font-black uppercase text-slate-500 block">Subir y Editar Logo (PNG Recomendado)</label>
                        <input 
                            type="file" 
                            accept="image/*" 
                            onChange={handleFileSelect} 
                            className="text-xs text-slate-500 file:mr-3 file:py-2.5 file:px-5 file:rounded-xl file:border-0 file:text-[10px] file:font-black file:uppercase file:bg-indigo-600 file:text-white cursor-pointer hover:file:bg-indigo-700 transition-all" 
                        />
                        <p className="text-[9px] text-slate-400 font-medium">Al seleccionar un archivo se abrirá el editor de recorte y encuadre.</p>
                    </div>

                    <div className="flex flex-col items-center justify-center p-4 bg-white rounded-2xl border border-slate-200 min-h-[120px]">
                        <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-2">Vista Previa Actual</span>
                        {companyLogoUrl ? (
                            <img src={companyLogoUrl} alt="Logo Empresa" className="h-16 w-auto object-contain max-w-[220px]" />
                        ) : (
                            <span className="text-xs font-bold text-slate-300 uppercase">Sin logo configurado</span>
                        )}
                    </div>
                </div>
            </div>

            {/* SECCIÓN 2: POLÍTICAS DE TARDANZAS Y ALMUERZOS */}
            <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 space-y-6">
                <div>
                    <h2 className="text-xl font-black text-slate-900">Políticas de Tardanzas y Tolerancia</h2>
                    <p className="text-slate-400 font-bold uppercase text-[10px] tracking-widest mt-0.5">
                        Límites de tiempo y penalizaciones automáticas del sistema
                    </p>
                </div>

                <div className="grid md:grid-cols-2 gap-5">
                    <div>
                        <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Margen de Gracia Entrada (Minutos)</label>
                        <input 
                            type="number" 
                            value={gracePeriodMinutes} 
                            onChange={e => setGracePeriodMinutes(e.target.value)} 
                            className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" 
                        />
                    </div>
                    <div>
                        <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Máx. Tardanzas Permitidas al Mes</label>
                        <input 
                            type="number" 
                            value={maxTardinessAllowed} 
                            onChange={e => setMaxTardinessAllowed(e.target.value)} 
                            className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" 
                        />
                    </div>
                    <div>
                        <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Límite Máximo de Almuerzo (Minutos)</label>
                        <input 
                            type="number" 
                            value={lunchLimitMinutes} 
                            onChange={e => setLunchLimitMinutes(e.target.value)} 
                            className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" 
                        />
                    </div>
                    <div>
                        <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Acción ante Exceso de Tardanzas</label>
                        <select 
                            value={tardinessPenaltyAction} 
                            onChange={e => setTardinessPenaltyAction(e.target.value)} 
                            className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" 
                        >
                            <option value="deduct_minutes">Descontar minutos exactos de planilla</option>
                            <option value="warning">Solo emitir alerta de auditoría</option>
                            <option value="deduct_half_day">Descontar medio día tras 3 tardanzas</option>
                        </select>
                    </div>
                </div>
            </div>

            {/* SECCIÓN 3: LEYES LABORALES Y TASAS DE PLANILLA */}
            <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 space-y-6">
                <div>
                    <h2 className="text-xl font-black text-slate-900">Leyes Laborales y Tasas de Nómina (Nicaragua)</h2>
                    <p className="text-slate-400 font-bold uppercase text-[10px] tracking-widest mt-0.5">
                        Tasas patronales de seguridad social y acumulación vacacional de ley
                    </p>
                </div>

                <div className="grid md:grid-cols-2 gap-5">
                    <div>
                        <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">INSS Patronal (%)</label>
                        <input 
                            type="number" 
                            step="0.1" 
                            value={inssRate} 
                            onChange={e => setInssRate(e.target.value)} 
                            className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" 
                        />
                        <span className="text-[9px] text-slate-400 font-medium mt-1 block">
                            21.5% para empresas de menos de 50 trabajadores • 22.5% para 50 a más.
                        </span>
                    </div>
                    <div>
                        <label className="text-[10px] font-black uppercase text-slate-400 block mb-1">Acumulación Vacaciones (Días / Mes)</label>
                        <input 
                            type="number" 
                            step="0.1" 
                            value={vacRate} 
                            onChange={e => setVacRate(e.target.value)} 
                            className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none" 
                        />
                        <span className="text-[9px] text-slate-400 font-medium mt-1 block">
                            Estándar Código del Trabajo Art. 76 (2.5 días por mes trabajado).
                        </span>
                    </div>
                </div>
            </div>

            {/* BOTÓN GENERAL DE GUARDADO */}
            <button 
                onClick={handleSaveAllSettings} 
                className="w-full py-5 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-3xl uppercase tracking-widest text-xs shadow-xl active:scale-98 transition-all"
            >
                Guardar Toda la Configuración
            </button>

            {/* MODAL FLOTANTE DE RECORTE Y ZOOM */}
            {showCropModal && (
                <div className="fixed inset-0 bg-slate-900/80 z-[130] flex items-center justify-center p-4 fade-in" onClick={() => setShowCropModal(false)}>
                    <div className="bg-white rounded-[3rem] w-full max-w-lg p-6 shadow-2xl space-y-5 border-t-[10px] border-indigo-600" onClick={e=>e.stopPropagation()}>
                        <div className="flex justify-between items-center border-b pb-3">
                            <div>
                                <h3 className="font-black text-lg text-slate-900">Ajustar y Recortar Logo</h3>
                                <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wider">Arrastra para mover y usa el zoom para encuadrar</p>
                            </div>
                            <button onClick={() => setShowCropModal(false)} className="p-2 bg-slate-50 rounded-full text-slate-400 hover:text-slate-600">
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"></path></svg>
                            </button>
                        </div>

                        <div className="flex justify-center bg-slate-100 p-4 rounded-3xl overflow-hidden border relative">
                            <div className="relative">
                                <canvas 
                                    ref={canvasRef} 
                                    width={360} 
                                    height={200} 
                                    onMouseDown={handleMouseDown}
                                    onMouseMove={handleMouseMove}
                                    onMouseUp={handleMouseUp}
                                    onMouseLeave={handleMouseUp}
                                    className="cursor-move rounded-2xl shadow-inner bg-transparent" 
                                />
                                <div className="absolute inset-3 border-2 border-dashed border-indigo-400/80 rounded-xl pointer-events-none"></div>
                            </div>
                        </div>

                        <div className="space-y-1.5 px-2">
                            <div className="flex justify-between text-xs font-black text-slate-600">
                                <span>Zoom</span>
                                <span>{zoomScale.toFixed(1)}x</span>
                            </div>
                            <input 
                                type="range" 
                                min="0.5" 
                                max="3.0" 
                                step="0.1" 
                                value={zoomScale} 
                                onChange={e => setZoomScale(parseFloat(e.target.value))} 
                                className="w-full h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-indigo-600" 
                            />
                        </div>

                        <div className="flex gap-3 pt-2">
                            <button onClick={() => setShowCropModal(false)} className="flex-1 py-3.5 bg-slate-100 text-slate-600 rounded-2xl font-black uppercase text-[10px]">
                                Cancelar
                            </button>
                            <button 
                                onClick={handleApplyCropAndSave} 
                                disabled={isSavingLogo}
                                className="flex-1 py-3.5 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-lg active:scale-95 transition-all flex items-center justify-center gap-2"
                            >
                                {isSavingLogo ? "Guardando..." : "Recortar y Guardar Logo"}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};