import React, { useMemo, useState } from 'react';
import { Calendar, Building2, ChevronRight } from 'lucide-react';

/**
 * Mapa de cores por status de coluna.
 */
const COLUMN_STYLES = {
    'Admissão':                  { header: 'bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-200', accent: 'border-slate-300 dark:border-slate-600' },
    'Experiência':               { header: 'bg-indigo-50 dark:bg-indigo-950/40 text-indigo-700 dark:text-indigo-300', accent: 'border-indigo-300 dark:border-indigo-700' },
    'Vencimento de Experiência': { header: 'bg-orange-50 dark:bg-orange-950/30 text-orange-700 dark:text-orange-300', accent: 'border-orange-300 dark:border-orange-600' },
    'Prorrogação':               { header: 'bg-emerald-50 dark:bg-emerald-950/30 text-emerald-700 dark:text-emerald-300', accent: 'border-emerald-300 dark:border-emerald-600' }
};

const STATUS_BADGE = {
    'Admissão':                  'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300',
    'Experiência':               'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300',
    'Vencimento de Experiência': 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300',
    'Prorrogação':               'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300'
};

/**
 * Card individual do Kanban de Contratos de Experiência.
 */
const ContractCard = ({ contract, onCardClick, onDragStart }) => {
    const style = COLUMN_STYLES[contract.global_status] || COLUMN_STYLES['Admissão'];

    return (
        <div
            draggable
            onDragStart={onDragStart}
            onClick={() => onCardClick?.(contract)}
            className={`
                bg-white dark:bg-white/[0.03] rounded-2xl border border-slate-200 dark:border-white/8
                p-4 cursor-pointer select-none
                hover:shadow-md hover:border-indigo-300/50 dark:hover:border-indigo-700/40
                active:scale-[0.98] transition-all duration-200 group
            `}
        >
            {/* Colaborador Avatar & Info */}
            <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-2xl bg-indigo-500/10 flex items-center justify-center text-indigo-600 dark:text-indigo-400 font-bold text-[11px] flex-shrink-0">
                    {contract.nome_colaborador 
                        ? contract.nome_colaborador.trim().split(' ').slice(0, 2).map(p => p[0]).join('').toUpperCase()
                        : `#${contract.idcolaborador}`}
                </div>
                <div className="min-w-0">
                    <h4 className="text-[13px] font-bold text-slate-800 dark:text-white leading-tight truncate" title={contract.nome_colaborador}>
                        {contract.nome_colaborador || 'Sem nome'}
                    </h4>
                    <div className="flex items-center gap-1.5 mt-0.5">
                        <Building2 size={10} className="text-slate-400" />
                        <span className="text-[10px] font-semibold text-slate-400 truncate max-w-[150px]">
                            {contract.empresa || 'Empresa não informada'}
                        </span>
                    </div>
                </div>
            </div>

            {/* Datas */}
            <div className="space-y-2 mb-3">

                <div className="flex items-center justify-between">
                    <span className="text-[10px] uppercase tracking-wider font-semibold text-slate-400">Venc. Exp.</span>
                    <span className="text-xs font-bold text-orange-600 dark:text-orange-400 font-mono">
                        {contract.vencimento_exp || '—'}
                    </span>
                </div>
                <div className="flex items-center justify-between">
                    <span className="text-[10px] uppercase tracking-wider font-semibold text-slate-400">Prorrogação</span>
                    <span className="text-xs font-bold text-emerald-600 dark:text-emerald-400 font-mono">
                        {contract.prorrogacao_exp || '—'}
                    </span>
                </div>
            </div>

            {/* Footer: global_status badge + botão editar */}
            <div className="flex items-center justify-between pt-2 border-t border-slate-100 dark:border-white/5">
                <span className={`text-[9px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-lg ${STATUS_BADGE[contract.global_status] || STATUS_BADGE['Admissão']}`}>
                    {contract.global_status}
                </span>
                <ChevronRight size={14} className="text-slate-300 group-hover:text-indigo-500 group-hover:translate-x-0.5 transition-all" />
            </div>
        </div>
    );
};

/**
 * Coluna do Kanban com scroll interno.
 */
const KanbanColumn = ({ column, onCardClick, onCardMove }) => {
    const style = COLUMN_STYLES[column.id] || COLUMN_STYLES['Admissão'];

    const handleDragOver = (e) => e.preventDefault();

    const handleDrop = (e) => {
        e.preventDefault();
        const data = e.dataTransfer.getData('application/json');
        if (!data) return;
        const card = JSON.parse(data);
        if (card.global_status !== column.id) {
            // Prioriza idcolaborador para a rota de edição de status global
            onCardMove?.(card.idcolaborador || card.idcontrato_rh, column.id, card);
        }
    };

    return (
        <div
            className="flex flex-col min-w-[280px] max-w-[320px] flex-1"
            onDragOver={handleDragOver}
            onDrop={handleDrop}
        >
            {/* Cabeçalho da coluna */}
            <div className={`flex items-center justify-between px-4 py-3 rounded-2xl mb-3 ${style.header} border ${style.accent}`}>
                <span className="text-xs font-black uppercase tracking-widest">{column.title}</span>
                <span className="min-w-[24px] h-6 flex items-center justify-center bg-white/60 dark:bg-black/20 rounded-lg text-[10px] font-bold px-2">
                    {column.cards.length}
                </span>
            </div>

            {/* Cards com scroll */}
            <div className="flex-1 overflow-y-auto max-h-[calc(100vh-320px)] pr-1 custom-scrollbar space-y-3">
                {column.cards.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-12 text-slate-300 dark:text-slate-600">
                        <Calendar size={28} className="mb-2 opacity-40" />
                        <p className="text-[10px] font-bold uppercase tracking-widest opacity-60">Nenhum contrato</p>
                    </div>
                ) : (
                    column.cards.map(card => (
                        <ContractCard
                            key={card.idcontrato_rh || card.idcolaborador}
                            contract={card}
                            onCardClick={onCardClick}
                            onDragStart={(e) => {
                                e.dataTransfer.setData('application/json', JSON.stringify(card));
                            }}
                        />
                    ))
                )}
            </div>
        </div>
    );
};

/**
 * Kanban customizado para Contratos de Experiência do RH.
 * Layout de card com: empresa, data_admissao, vencimento_exp, prorrogacao_exp, global_status.
 */
export const ExperienceContractKanban = ({ contracts, onCardMove, onCardClick, loading }) => {

    const COLUMNS_DEF = [
        { id: 'Experiência',               title: 'Experiência' },
        { id: 'Vencimento de Experiência', title: 'Vencimento de Experiência' },
        { id: 'Prorrogação',               title: 'Prorrogação' }
    ];

    const columns = useMemo(() =>
        COLUMNS_DEF.map(col => ({
            ...col,
            cards: contracts.filter(c =>
                col.id === 'Admissão'
                    ? (c.global_status === 'Admissão' || !c.global_status)
                    : c.global_status === col.id
            )
        }))
    , [contracts]);

    if (loading) {
        return (
            <div className="flex h-full w-full items-center justify-center min-h-[400px]">
                <div className="flex flex-col items-center gap-4">
                    <div className="w-12 h-12 border-4 border-indigo-500/20 border-t-indigo-500 rounded-full animate-spin" />
                    <p className="text-slate-500 font-medium animate-pulse uppercase tracking-widest text-[10px]">Carregando Kanban...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="flex gap-4 h-full overflow-x-auto pb-4 custom-scrollbar">
            {columns.map(col => (
                <KanbanColumn
                    key={col.id}
                    column={col}
                    onCardClick={onCardClick}
                    onCardMove={onCardMove}
                />
            ))}
        </div>
    );
};
