import React from 'react';
import ExcelTable from './ExcelTable';
import { Building2, CalendarDays } from 'lucide-react';

// ─── Helpers de Data ─────────────────────────────────────────────────────────

const safeParseDate = (str) => {
    if (!str) return null;
    const m = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
    if (m) return new Date(Number(m[3]), Number(m[2]) - 1, Number(m[1]));
    const d = new Date(str);
    return isNaN(d.getTime()) ? null : d;
};

const formatDate = (str) => {
    if (!str) return '-';
    if (/^\d{2}\/\d{2}\/\d{4}$/.test(str)) return str;
    const d = safeParseDate(str);
    return d ? d.toLocaleDateString('pt-BR') : '-';
};

// ─── Badge de Status ──────────────────────────────────────────────────────────

const STATUS_STYLES = {
    'Admissão': {
        cls: 'bg-slate-100 text-slate-700 border-slate-200 dark:bg-slate-500/10 dark:text-slate-300 dark:border-slate-500/20',
        dot: 'bg-slate-400',
    },
    'Experiência': {
        cls: 'bg-amber-100 text-amber-700 border-amber-200 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/20',
        dot: 'bg-amber-500',
    },
    'Prorrogação': {
        cls: 'bg-emerald-100 text-emerald-700 border-emerald-200 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20',
        dot: 'bg-emerald-500',
    },
    'Vencimento de Experiência': {
        cls: 'bg-orange-100 text-orange-700 border-orange-200 dark:bg-orange-500/10 dark:text-orange-400 dark:border-orange-500/20',
        dot: 'bg-orange-500',
    },
};

const StatusBadge = ({ status }) => {
    const style = STATUS_STYLES[status] || {
        cls: 'bg-slate-100 text-slate-500 border-slate-200 dark:bg-slate-800 dark:text-slate-400 dark:border-slate-700',
        dot: 'bg-slate-400',
    };
    return (
        <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-semibold uppercase border shadow-sm tracking-wide whitespace-nowrap ${style.cls}`}>
            <span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${style.dot}`} />
            {status || 'Não Definido'}
        </span>
    );
};

// ─── Avatar com iniciais ──────────────────────────────────────────────────────

const ColaboradorAvatar = ({ nome, id }) => {
    const initials = nome
        ? nome.trim().split(' ').slice(0, 2).map(p => p[0]).join('').toUpperCase()
        : `#${id}`;

    return (
        <div className="flex items-center gap-3 w-full">
            <div className="w-9 h-9 rounded-full bg-indigo-500/10 flex-shrink-0 flex items-center justify-center text-indigo-600 dark:text-indigo-400 font-bold text-[11px] select-none">
                {initials}
            </div>
            <div className="flex flex-col min-w-0 flex-1">
                <span
                    className="font-semibold text-slate-800 dark:text-slate-200 leading-tight truncate block text-[13px]"
                    title={nome || `ID ${id}`}
                >
                    {nome || <span className="text-slate-400 italic font-normal text-xs">Sem nome</span>}
                </span>
                <span className="text-[11px] text-slate-400 font-medium">ID {id}</span>
            </div>
        </div>
    );
};

// ─── Coluna de Data ───────────────────────────────────────────────────────────

const DateCell = ({ value }) => (
    <div className="flex items-center gap-1.5 text-[13px] font-mono text-slate-600 dark:text-slate-300">
        <CalendarDays size={13} className="text-slate-400 flex-shrink-0" />
        {formatDate(value)}
    </div>
);

// ─── Componente Principal ─────────────────────────────────────────────────────

export const ExperienceContractTable = ({ contracts, loading, onEdit }) => {

    const columns = [
        {
            field: 'idcolaborador',
            header: 'ID',
            width: 65,
            className: 'font-mono text-[13px] text-slate-500',
        },
        {
            field: 'nome_colaborador',
            header: 'Colaborador',
            width: 270,
            render: (row) => <ColaboradorAvatar nome={row.nome_colaborador} id={row.idcolaborador} />,
        },
        {
            field: 'empresa',
            header: 'Empresa',
            width: 260,
            render: (row) => (
                <div className="flex items-center gap-2 min-w-0">
                    <Building2 size={13} className="text-slate-400 flex-shrink-0" />
                    <span className="text-[13px] text-slate-600 dark:text-slate-300 font-medium truncate" title={row.empresa}>
                        {row.empresa || '-'}
                    </span>
                </div>
            ),
        },
        {
            field: 'vencimento_exp',
            header: 'Vencimento Exp.',
            width: 148,
            render: (row) => <DateCell value={row.vencimento_exp} />,
        },
        {
            field: 'prorrogacao_exp',
            header: 'Prorrogação Exp.',
            width: 155,
            render: (row) => <DateCell value={row.prorrogacao_exp} />,
        },
        {
            field: 'global_status',
            header: 'Status',
            render: (row) => <StatusBadge status={row.global_status} />,
        },
    ];

    const filterDefs = [
        { field: 'empresa',       type: 'select', label: 'Empresa' },
        { field: 'global_status', type: 'select', label: 'Status'  },
    ];

    return (
        <div
            className="h-full bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5 overflow-hidden flex flex-col shadow-xl shadow-slate-200/50 dark:shadow-none"
            style={{ minHeight: 0 }}
        >
            <ExcelTable
                data={contracts}
                columns={columns}
                filterDefs={filterDefs}
                loading={loading}
                pageSize={10}
                onEdit={onEdit}
                onRowClick={onEdit}
            />
        </div>
    );
};
