import { useState, useRef, useEffect } from 'react';
import './Generator.css';
import { renderQRCode, downloadIDCards, downloadBulkIDCards, getXLSXLib, clientTemplates } from './script/script.jsx';
import { uploadEmployeePhoto, saveClienteProyecto } from './services/storage.js';
import { supabase } from "./services/supabase";

// Convierte datos binarios recibidos (base64, buffer, array de bytes) en un Blob URL local de forma robusta
const convertBinaryToBlobUrl = (data) => {
    if (!data) return null;
    try {
        if (typeof data === 'object' && data.type === 'Buffer' && Array.isArray(data.data)) {
            const byteArray = new Uint8Array(data.data);
            const blob = new Blob([byteArray], { type: 'image/jpeg' });
            return URL.createObjectURL(blob);
        }

        if (Array.isArray(data)) {
            const byteArray = new Uint8Array(data);
            const blob = new Blob([byteArray], { type: 'image/jpeg' });
            return URL.createObjectURL(blob);
        }

        if (typeof data === 'string') {
            const cleanBase64 = data.replace(/^data:image\/\w+;base64,/, "");
            const byteCharacters = atob(cleanBase64);
            const byteNumbers = new Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            const byteArray = new Uint8Array(byteNumbers);
            const blob = new Blob([byteArray], { type: 'image/jpeg' });
            return URL.createObjectURL(blob);
        }
    } catch (e) {
        // ignore
    }
    return null;
};

export default function IdCardGenerator() {
    // --- Estados formulario individual ───
    const [name, setName] = useState('');
    const [role, setRole] = useState('');
    const [language, setLanguage] = useState('Esp');
    const [selectedClient, setSelectedClient] = useState('Generico');
    const [employeeId, setEmployeeId] = useState('');
    const [photoSrc, setPhotoSrc] = useState('');
    const [photoFile, setPhotoFile] = useState(null);
    const [photoProcessing, setPhotoProcessing] = useState(false);
    const [downloadStatus, setDownloadStatus] = useState({ processing: false, text: '⬇ Descargar' });

    // Bloquea el botón Descargar hasta que nombre, puesto e ID estén llenos
    const isFormComplete = name.trim() && role.trim() && employeeId.trim();

    // --- Estados Lote / Excel Masivo ───
    const [bulkEmployees, setBulkEmployees] = useState([]);
    const [bulkStatusText, setBulkStatusText] = useState('');
    const [bulkDownloadStatus, setBulkDownloadStatus] = useState({ processing: false, text: '⬇ Descargar' });
    const [showTooltip, setShowTooltip] = useState(false);

    const fileInputRef = useRef(null);
    const excelInputRef = useRef(null);
    const qrCanvasRef = useRef(null);

    const baseUrl = import.meta.env.BASE_URL.endsWith('/')
        ? import.meta.env.BASE_URL
        : `${import.meta.env.BASE_URL}/`;

    useEffect(() => {
        if (qrCanvasRef.current) {
            renderQRCode(employeeId, qrCanvasRef.current);
        }
    }, [employeeId]);

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

        setPhotoFile(file);
        setPhotoSrc(URL.createObjectURL(file));
        setPhotoProcessing(true);

        try {
            const editedBlob = await processPhotoWithAI(file);
            const editedUrl = URL.createObjectURL(editedBlob);
            setPhotoSrc(editedUrl);
            setPhotoFile(new File([editedBlob], file.name, { type: editedBlob.type || 'image/jpeg' }));
        } catch (error) {
            alert('No se pudo procesar la foto con IA. Se usará la foto original para la vista previa.');
        } finally {
            setPhotoProcessing(false);
        }
    };

    const processPhotoWithAI = async (file) => {
        const N8N_WEBHOOK_URL = import.meta.env.VITE_N8N_WEBHOOK_URL;
        const TOKEN_SECRETO = import.meta.env.VITE_WEBHOOK_TOKEN;

        const formData = new FormData();
        formData.append('edited', file, file.name);
        formData.append('name', name);
        formData.append('role', role);
        formData.append('employeeId', employeeId);
        formData.append('fechaProcesado', new Date().toISOString());

        const response = await fetch(N8N_WEBHOOK_URL, {
            method: 'POST',
            headers: {
                'Authorization': TOKEN_SECRETO
            },
            body: formData
        });

        if (!response.ok) {
            throw new Error(`El servidor de n8n rechazó la petición (Código: ${response.status})`);
        }

        const contentType = response.headers.get('content-type') || '';
        if (contentType.includes('application/json')) {
            const data = await response.json();
            const bin = data.edited || data.data || data.foto_processed_base64 || data.photo || data.binary || (Array.isArray(data) && (data[0]?.edited || data[0]?.data));
            const blobUrl = convertBinaryToBlobUrl(bin);
            if (!blobUrl) throw new Error('n8n no devolvió un binario válido.');
            const blob = await (await fetch(blobUrl)).blob();
            return blob;
        }

        const blob = await response.blob();
        if (!blob || blob.size === 0) throw new Error('n8n devolvió un binario vacío.');
        return blob;
    };

    const handleEmployeeIdChange = (e) => {
        const rawValue = e.target.value;
        const cleanValue = rawValue.replace(/[-\s]/g, '');
        setEmployeeId(cleanValue);
    };

    const enviarDatosAn8n = async (datosEmpleados) => {
        const N8N_WEBHOOK_URL = import.meta.env.VITE_N8N_WEBHOOK_URL;
        const TOKEN_SECRETO = import.meta.env.VITE_WEBHOOK_TOKEN;

        try {
            const response = await fetch(N8N_WEBHOOK_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': TOKEN_SECRETO
                },
                body: JSON.stringify({
                    empleados: datosEmpleados,
                    total: datosEmpleados.length,
                    fechaProcesado: new Date().toISOString()
                })
            });

            if (!response.ok) {
                throw new Error(`El servidor de n8n rechazó la petición (Código: ${response.status})`);
            }

            const resData = await response.json();
            return Array.isArray(resData) ? resData : (resData.empleados || resData.data || []);
        } catch (error) {
            throw error;
        }
    };

    const handleBulkSupabaseSync = async (cedula, blobData, currentEmployee) => {
        const cleanCedula = String(cedula).replace(/[-\s]/g, '');
        if (!cleanCedula) return;

        try {
            const clienteProyectoValue = currentEmployee?.selectedClient || 'Generico';

            // 1) Guardar cédula + cliente_proyecto en carnet_empleados_creados_glm
            await saveClienteProyecto(cleanCedula, clienteProyectoValue);

            // 2) Subir foto al storage
            const customFile = new File([blobData], `${cleanCedula}.jpg`, { type: 'image/jpeg' });
            const remoteStorageUrl = await uploadEmployeePhoto(cleanCedula, customFile);

            // 3) Guardar URL de foto
            if (remoteStorageUrl) {
                await supabase.rpc("save_employee_photo", {
                    p_employee_number: cleanCedula,
                    p_photo_url: remoteStorageUrl
                });
            }
        } catch (error) {
            // silent
        }
    };

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

        setBulkStatusText('Leyendo documento...');
        try {
            const XLSXLib = await getXLSXLib();
            const reader = new FileReader();

            reader.onload = async (evt) => {
                try {
                    const bstr = evt.target.result;
                    const wb = XLSXLib.read(bstr, { type: 'binary' });
                    const wsname = wb.SheetNames[0];
                    const ws = wb.Sheets[wsname];
                    const jsonRows = XLSXLib.utils.sheet_to_json(ws);

                    if (jsonRows.length === 0) {
                        setBulkStatusText('❌ El archivo está vacío.');
                        return;
                    }

                    const formatted = jsonRows.map((row) => {
                        let rawLang = String(row.lenguaje || 'Esp').trim().toLowerCase();
                        if (rawLang.includes('es') || rawLang.includes('esp')) {
                            rawLang = 'Esp';
                        } else if (rawLang.includes('en') || rawLang.includes('ing')) {
                            rawLang = 'Ing';
                        } else {
                            rawLang = 'Esp';
                        }

                        let rawClient = String(row['cliente/proyecto'] || 'Generico')
                            .trim()
                            .normalize("NFD")
                            .replace(/[\u0300-\u036f]/g, "");

                        const lowerClient = rawClient.toLowerCase();
                        if (lowerClient.includes('nestle')) rawClient = 'Nestle';
                        else if (lowerClient.includes('claro')) rawClient = 'Claro';
                        else if (lowerClient.includes('colgate')) rawClient = 'Colgate';
                        else if (lowerClient.includes('kitchenaid') || lowerClient.includes('kitchen')) rawClient = 'KitchenAid';
                        else if (lowerClient.includes('kraft')) rawClient = 'Kraft';
                        else if (lowerClient.includes('motorola')) rawClient = 'Motorola';
                        else if (lowerClient.includes('p&g') || lowerClient.includes('p y g')) rawClient = 'P&G';
                        else if (lowerClient.includes('philip') || lowerClient.includes('morris')) rawClient = 'Philip Morris';
                        else if (lowerClient.includes('whirlpool')) rawClient = 'Whirlpool';
                        else rawClient = 'Generico';

                        const cleanedCedula = String(row.cedula || '').replace(/[-\s]/g, '');

                        return {
                            name: String(row.nombre || '').trim(),
                            role: String(row.puesto || '').trim(),
                            selectedClient: rawClient,
                            language: rawLang,
                            employeeId: cleanedCedula,
                            fotoUrl: String(row.foto_url || '').trim()
                        };
                    }).filter(emp => emp.name && emp.role && emp.employeeId);

                    setBulkEmployees(formatted);
                    setBulkStatusText(`✅ ¡Cargados ${formatted.length} colaboradores! Listo para procesar.`);
                    setBulkDownloadStatus({ processing: false, text: '⬇ Descargar' });

                } catch (innerErr) {
                    setBulkStatusText('❌ Error de lectura. Revisa el formato de columnas.');
                }
            };
            reader.readAsBinaryString(file);
        } catch (err) {
            setBulkStatusText('❌ Error cargando el motor XLSX.');
        }
    };

    const triggerBulkDownload = async () => {
        if (bulkEmployees.length === 0) return;

        setBulkDownloadStatus({ processing: true, text: '🔄 Descargando...' });
        setBulkStatusText('Descargando retratos...');

        try {
            const resultadosN8n = await enviarDatosAn8n(bulkEmployees);
            setBulkStatusText('Generando frentes, reversos y empaquetando en carpetas locales...');

            const employeesReadyForRender = bulkEmployees.map((originalEmp, index) => {
                const n8nEmp = resultadosN8n[index] || resultadosN8n.find(e => e.employeeId === originalEmp.employeeId) || {};

                const base64Source = n8nEmp.data || n8nEmp.foto_processed_base64 || originalEmp.data;
                let finalPhotoUrl = convertBinaryToBlobUrl(base64Source) || originalEmp.fotoUrl;

                const validClient = n8nEmp.selectedClient || originalEmp.selectedClient || 'Generico';
                const validLang = n8nEmp.language || originalEmp.language || 'Esp';

                return {
                    name: n8nEmp.name || originalEmp.name,
                    role: n8nEmp.role || originalEmp.role,
                    selectedClient: validClient,
                    language: validLang,
                    employeeId: n8nEmp.employeeId || originalEmp.employeeId,
                    fotoUrl: finalPhotoUrl
                };
            });

            await downloadBulkIDCards({
                employees: employeesReadyForRender,
                baseUrl,
                onStateChange: null,
                onProcessEmployeePhoto: (cedula, blobData) => {
                    const currentEmp = employeesReadyForRender.find(emp => emp.employeeId === cedula);
                    return handleBulkSupabaseSync(cedula, blobData, currentEmp);
                }
            });

            setBulkStatusText(`✅ ¡Lote completado! ${employeesReadyForRender.length} carnets procesados.`);
            setBulkEmployees([]);

        } catch (error) {
            setBulkStatusText(`❌ Error al procesar: ${error.message || error}`);
        } finally {
            setBulkDownloadStatus({ processing: false, text: '⬇ Descargar' });
        }
    };

    const triggerDownload = async () => {
        if (!validateForm()) return;
        setDownloadStatus({ processing: true, text: '🔄 Descargando...' });
        try {
            await saveClienteProyecto(employeeId, selectedClient);

            if (photoFile) {
                const photoUrl = await uploadEmployeePhoto(employeeId, photoFile);
                await supabase.rpc("save_employee_photo", {
                    p_employee_number: employeeId,
                    p_photo_url: photoUrl
                });
            }

            await downloadIDCards({
                name, role, selectedClient, language, photoSrc,
                baseUrl,
                qrCanvas: qrCanvasRef.current,
                onStateChange: setDownloadStatus
            });
        } catch (err) {
            alert(err.message);
            setDownloadStatus({ processing: false, text: '⬇ Descargar' });
        }
    };

    const validateForm = () => {
        if (!name.trim()) { alert("Debe ingresar el nombre."); return false; }
        if (!role.trim()) { alert("Debe ingresar el puesto."); return false; }
        if (!employeeId.trim()) { alert("Debe ingresar el ID del empleado."); return false; }
        if (!photoFile) { alert("Debe subir la foto del colaborador."); return false; }
        return true;
    };

    return (
        <>
            <div className="page-title">
                <h1>GLM ID Card Generator</h1>
                <p>GomezLee Marketing · Carnet Corporativo CR80</p>
            </div>

            <div className="main-container" style={{ display: 'flex', gap: '20px', alignItems: 'flex-start' }}>
                {/* FORMULARIO MASIVO EXCEL */}
                <div className="panel" style={{ minWidth: '320px' }}>
                    <div className="preview-badge" style={{ background: '#FFF3E0', color: '#E65100' }}>
                        <div className="dot" style={{ background: '#E65100' }}></div>
                        <span>Módulo de Lotes Automáticos</span>
                    </div>

                    <div className="panel-section">
                        <div className="panel-section-title" style={{ display: 'flex', alignItems: 'center', gap: '6px', position: 'relative' }}>
                            <span>Carga Masiva de Colaboradores</span>
                            <div
                                style={{
                                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                                    width: '16px', height: '16px', borderRadius: '50%',
                                    background: '#cbd5e1', color: '#334155', fontSize: '11px',
                                    fontWeight: 'bold', cursor: 'help', userSelect: 'none'
                                }}
                                onMouseEnter={() => setShowTooltip(true)}
                                onMouseLeave={() => setShowTooltip(false)}
                            >
                                ?
                            </div>

                            {showTooltip && (
                                <div style={{
                                    position: 'absolute', top: '24px', left: '0', right: '0',
                                    background: '#1e293b', color: '#ffffff', padding: '10px',
                                    borderRadius: '6px', fontSize: '11px', lineHeight: '1.4',
                                    zIndex: '99', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)',
                                    fontWeight: 'normal', textTransform: 'none'
                                }}>
                                    Formato de columnas requeridas en el Excel: <br />
                                    <b style={{ color: '#6CC24A' }}>nombre, puesto, cliente/proyecto, cedula, lenguaje, foto_url</b>.<br />
                                </div>
                            )}
                        </div>

                        <div className="upload-btn" style={{ background: '#475569', marginTop: '12px' }} onClick={() => excelInputRef.current.click()}>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                                <polyline points="14 2 14 8 20 8" />
                                <line x1="16" y1="13" x2="8" y2="13" />
                                <line x1="16" y1="17" x2="8" y2="17" />
                            </svg>
                            Seleccionar Archivo Excel
                        </div>
                        <input type="file" accept=".xlsx, .xls, .csv" style={{ display: 'none' }} ref={excelInputRef} onChange={handleExcelUpload} />

                        {bulkStatusText && (
                            <div style={{ fontSize: '12px', marginTop: '8px', fontWeight: '500', color: '#475569' }}>
                                {bulkStatusText}
                            </div>
                        )}
                    </div>

                    <div className="divider"></div>

                    <div className="panel-section">
                        <div className="panel-section-title">Exportar Lote</div>
                        <button
                            className="export-btn blue"
                            disabled={bulkDownloadStatus.processing || bulkEmployees.length === 0}
                            onClick={triggerBulkDownload}
                            style={{ opacity: bulkEmployees.length === 0 ? 0.6 : 1 }}
                        >
                            {bulkDownloadStatus.text}
                        </button>
                    </div>
                </div>

                {/* FORMULARIO INDIVIDUAL */}
                <div className="panel">
                    <div className="preview-badge">
                        <div className="dot"></div>
                        <span>Vista previa en tiempo real</span>
                    </div>

                    <div className="panel-section">
                        <div className="panel-section-title">Colaborador</div>
                        <div className="field">
                            <label>Nombre</label>
                            <input type="text" placeholder="Ej: Alexi Zabala" value={name} onChange={(e) => setName(e.target.value)} />
                        </div>
                        <div className="field">
                            <label>Puesto</label>
                            <input type="text" placeholder="Ej: Mercaderista" value={role} onChange={(e) => setRole(e.target.value)} />
                        </div>
                        <div className="upload-btn" onClick={() => !photoProcessing && fileInputRef.current.click()} style={{ opacity: photoProcessing ? 0.6 : 1, cursor: photoProcessing ? 'wait' : 'pointer' }}>
                            {photoProcessing ? '⏳ Procesando foto con IA...' : 'Subir foto del colaborador'}
                        </div>
                        <input type="file" accept="image/*" style={{ display: 'none' }} ref={fileInputRef} onChange={handlePhotoUpload} />
                    </div>

                    <div className="divider"></div>

                    <div className="panel-section">
                        <div className="panel-section-title">Cliente / Proyecto</div>
                        <div className="lang-container">
                            <button type="button" className={`lang-btn ${language === 'Esp' ? 'active' : ''}`} onClick={() => setLanguage('Esp')}>Español</button>
                            <button type="button" className={`lang-btn ${language === 'Ing' ? 'active' : ''}`} onClick={() => setLanguage('Ing')}>Inglés</button>
                        </div>
                        <div className="field">
                            <label>Seleccionar Cliente</label>
                            <select value={selectedClient} onChange={(e) => setSelectedClient(e.target.value)}>
                                <option value="Generico">Genérico (Por defecto)</option>
                                <option value="Claro">Claro</option>
                                <option value="Colgate">Colgate</option>
                                <option value="KitchenAid">KitchenAid</option>
                                <option value="Kraft">Kraft</option>
                                <option value="Motorola">Motorola</option>
                                <option value="Nestle">Nestle</option>
                                <option value="P&G">P&G</option>
                                <option value="Philip Morris">Philip Morris International</option>
                                <option value="Whirlpool">Whirlpool</option>
                            </select>
                        </div>
                    </div>

                    <div className="divider"></div>

                    <div className="panel-section">
                        <div className="panel-section-title">Código QR</div>
                        <div className="field">
                            <label>ID del empleado / Cédula</label>
                            <input
                                type="text"
                                placeholder="Ej: 123456789 (Sin guiones ni espacios)"
                                value={employeeId}
                                onChange={handleEmployeeIdChange}
                            />
                        </div>
                        <button className="export-btn" style={{ background: '#6CC24A', marginTop: '2px' }} onClick={() => renderQRCode(employeeId, qrCanvasRef.current)}>
                            ⟳ Generar QR
                        </button>
                    </div>

                    <div className="divider"></div>

                    <div className="panel-section">
                        <div className="panel-section-title">Exportar</div>
                        <button className="export-btn blue" disabled={downloadStatus.processing || !isFormComplete} onClick={triggerDownload} style={{ opacity: (!isFormComplete || downloadStatus.processing) ? 0.6 : 1 }}>
                            {downloadStatus.text}
                        </button>
                    </div>
                </div>

                {/* VISTA PREVIA */}
                <div className="stage">
                    <div className="card-wrap">
                        <div className="card-label">Frente</div>
                        <div className="card" id="cardFront" style={{ backgroundImage: `url('${baseUrl}images/AF GLM Frente.png')` }}>
                            <div className="front-photo-frame" style={{ position: 'relative', overflow: 'hidden' }}>
                                {photoSrc ? (
                                    <img src={photoSrc} alt="Foto Colaborador" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                                ) : (null)}
                                {photoProcessing && (
                                    <div style={{
                                        position: 'absolute', inset: 0, display: 'flex',
                                        alignItems: 'center', justifyContent: 'center',
                                        background: 'rgba(0,0,0,0.45)', color: '#fff',
                                        fontSize: '13px', fontWeight: '600', textAlign: 'center', padding: '8px'
                                    }}>
                                        ⏳ Editando foto con IA...
                                    </div>
                                )}
                                {!photoSrc && (
                                    <svg className="placeholder-svg" viewBox="0 0 28 28" fill="none" style={{ width: '60%', height: '60%', opacity: 0.4 }}>
                                        <circle cx="14" cy="10" r="5.5" stroke="currentColor" strokeWidth="1.5" />
                                        <path d="M3 24c0-6 22-6 22 0" stroke="currentColor" strokeWidth="1.5" />
                                    </svg>
                                )}
                            </div>
                            <div className="front-dynamic-name">{name ? name.toUpperCase() : 'NOMBRE APELLIDO'}</div>
                            <div className="front-dynamic-role">{role ? role.toUpperCase() : 'PUESTO'}</div>
                        </div>
                    </div>

                    <div className="card-wrap">
                        <div className="card-label">Reverso</div>
                        <div
                            className="card"
                            id="cardBack"
                            style={{
                                backgroundImage: `url('${baseUrl}${(clientTemplates[language] || clientTemplates['Esp'])[selectedClient] || (clientTemplates[language] || clientTemplates['Esp'])['Generico']}')`
                            }}
                        >
                            <div className="back-qr-zone">
                                <canvas ref={qrCanvasRef} width={55} height={55}></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}