import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { supabase } from "../services/supabase";
import "./EmployeeCard.css";

function toDriveDirectUrl(url) {
    if (!url) return url;

    // Detectamos si es una URL de Google Drive
    if (url.includes("drive.google.com")) {
        // Expresión regular para extraer el ID
        const match = url.match(/(?:file\/d\/|id=)([a-zA-Z0-9_-]+)/);

        if (match) {
            const fileId = match[1];
            // Usamos el endpoint de thumbnail que no tiene problemas de CORS
            return `https://drive.google.com/thumbnail?id=${fileId}&sz=w1000`;
        }
    }

    // Si es de BambooHR u otra URL, la devolvemos tal cual
    return url;
}

export default function EmployeeCard() {

    const [searchParams] = useSearchParams();
    const employeeNumber = searchParams.get("id");

    const [employee, setEmployee] = useState(null);
    const [loading, setLoading] = useState(true);
    const [notFound, setNotFound] = useState(false);

    useEffect(() => {
        async function loadEmployee() {
            const { data, error } = await supabase
                .rpc("get_carnet_publico", { p_cedula: employeeNumber });

            if (error || !data || data.length === 0) {
                setNotFound(true);
            } else {
                setEmployee(data[0]);
            }
            setLoading(false);
        }
        loadEmployee();
    }, [employeeNumber]);

    if (loading) {
        return (
            <div className="page loading">
                <h2>Cargando...</h2>
            </div>
        );
    }

    if (notFound) {
        return (
            <div className="page not-found">
                <h1>Empleado no encontrado</h1>
            </div>
        );
    }

    console.log("1. URL original de Supabase:", employee.photo_url);

    // Procesamos la URL final directamente aquí
    const finalPhotoSrc = toDriveDirectUrl(employee.photo_url);

    console.log("2. URL final a renderizar:", finalPhotoSrc);

    const active = employee.status?.toLowerCase() === "active";

    return (
        <div className="page">
            <div className="employee-card">
                <div
                    className="header"
                    style={{
                        backgroundColor: active ? "#22c55e" : "#ef4444"
                    }}
                >
                    {active ? "Empleado Activo" : "Empleado No Activo"}
                </div>

                <div className="content">
                    {employee.photo_url ? (
                        <img
                            src={finalPhotoSrc} // <-- CORREGIDO: Usamos la variable ya procesada directamente
                            alt={employee.name}
                            style={{
                                width: "150px",
                                height: "150px",
                                objectFit: "cover",
                                borderRadius: "50%",
                                display: "block",
                                margin: "0 auto"
                            }}
                            className="employee-photo"
                        />
                    ) : (
                        <div className="employee-photo-placeholder">
                            Sin foto
                        </div>
                    )}

                    <div className="label">Nombre</div>
                    <div className="value">{employee.name}</div>

                    <div className="label">Puesto</div>
                    <div className="value">{employee.job_title}</div>

                    <div className="label">País</div>
                    <div className="value">{employee.country}</div>

                    <div className="label">Estado</div>
                    <div className="value">{employee.status}</div>
                </div>
            </div>
        </div>
    );
}