import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { 
    X, 
    Save, 
    ChevronRight,
    Briefcase,
    Calendar,
    Building2,
    User
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { 
    Select, 
    SelectContent, 
    SelectItem, 
    SelectTrigger, 
    SelectValue 
} from '@/components/ui/select';

/**
 * Converte data do formato DD/MM/YYYY (API) → YYYY-MM-DD (input type=date)
 */
const toInputDate = (val) => {
    if (!val) return '';
    // Já está no formato ISO
    if (/^\d{4}-\d{2}-\d{2}/.test(val)) return val.substring(0, 10);
    // Formato BR: DD/MM/YYYY
    const [d, m, y] = val.split('/');
    if (d && m && y) return `${y}-${m.padStart(2,'0')}-${d.padStart(2,'0')}`;
    return val;
};

/**
 * Sidebar customizada para formulário de Contrato de Experiência.
 * Mantendo o padrão estético premium do iT Guys.
 * Aceita `prefillData` para pré-popular dados ao abrir via painel de colaborador.
 */
export const ExperienceContractFormSidebar = ({ isOpen, onClose, onSubmit, initialData, prefillData }) => {
    const { register, handleSubmit, reset, setValue, watch } = useForm();

    useEffect(() => {
        if (initialData) {
            // Modo de edição: converte datas para formato ISO antes de popular o form
            const vals = {
                ...initialData,
                data_admissao:  toInputDate(initialData.data_admissao),
                vencimento_exp: toInputDate(initialData.vencimento_exp),
                prorrogacao_exp: toInputDate(initialData.prorrogacao_exp),
            };
            reset(vals);
            // setValue explícito nos campos Radix Select para garantir re-render correto
            setValue('empresa', initialData.empresa || 'B2B TRANSPORTES E LOGISTICAS LTDA');
            setValue('global_status', initialData.global_status || 'Admissão');
        } else if (prefillData) {
            // Modo de criação via painel de colaborador
            reset({
                idcolaborador: prefillData.idcolaborador || '',
                data_admissao: toInputDate(prefillData.data_admissao) || '',
                empresa: prefillData.empresa || 'B2B TRANSPORTES E LOGISTICAS LTDA',
                vencimento_exp: '',
                prorrogacao_exp: '',
                global_status: 'Admissão'
            });
            setValue('empresa', prefillData.empresa || 'B2B TRANSPORTES E LOGISTICAS LTDA');
        } else {
            // Modo de criação livre
            reset({
                idcolaborador: '',
                data_admissao: '',
                empresa: 'B2B TRANSPORTES E LOGISTICAS LTDA',
                vencimento_exp: '',
                prorrogacao_exp: '',
                global_status: 'Admissão'
            });
            setValue('empresa', 'B2B TRANSPORTES E LOGISTICAS LTDA');
        }
    }, [initialData, prefillData, reset, setValue, isOpen]);

    const handleFormSubmit = (data) => {
        onSubmit(data);
    };

    return (
        <AnimatePresence>
            {isOpen && (
                <>
                    <motion.div 
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        onClick={onClose}
                        className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[100]"
                    />
                    <motion.div 
                        initial={{ x: '100%' }}
                        animate={{ x: 0 }}
                        exit={{ x: '100%' }}
                        transition={{ type: 'spring', damping: 25, stiffness: 200 }}
                        className="fixed top-0 right-0 h-full w-full max-w-[480px] bg-white dark:bg-[#0a0a0a] border-l border-slate-200 dark:border-white/5 z-[101] shadow-2xl flex flex-col"
                    >
                        {/* Header */}
                        <div className="p-6 border-b border-slate-100 dark:border-white/5 flex items-center justify-between bg-zinc-50/50 dark:bg-white/2">
                            <div className="flex items-center gap-4">
                                <div className="p-3 bg-indigo-500/10 rounded-2xl">
                                    <Briefcase className="text-indigo-500" size={20} />
                                </div>
                                <div>
                                    <h2 className="text-lg font-bold text-slate-800 dark:text-white tracking-tight">
                                        {initialData ? 'Editar Contrato' : 'Novo Contrato'}
                                    </h2>
                                    <p className="text-[10px] text-slate-500 font-bold uppercase tracking-widest mt-0.5">Gestão de Experiência</p>
                                </div>
                            </div>
                            <button 
                                onClick={onClose}
                                className="p-2 hover:bg-slate-100 dark:hover:bg-white/5 rounded-xl transition-colors text-slate-400"
                            >
                                <X size={20} />
                            </button>
                        </div>

                        {/* Content */}
                        <form id="experience-contract-form" onSubmit={handleSubmit(handleFormSubmit)} className="flex-1 overflow-y-auto p-8 space-y-8 custom-scrollbar">
                            
                            {/* Colaborador ID — oculto, enviado automaticamente */}
                            <input type="hidden" {...register('idcolaborador')} />
                            {/* {
                                <div className="space-y-2">
                                    <div className="flex items-center gap-2 mb-1">
                                        <User size={14} className="text-indigo-500" />
                                        <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400">ID do Colaborador</Label>
                                    </div>
                                    <Input 
                                        {...register('idcolaborador', { required: true })}
                                        disabled={!!initialData || !!prefillData}
                                        placeholder="Ex: 12345"
                                        className="h-12 rounded-2xl bg-zinc-50 dark:bg-white/2 border-slate-200 dark:border-white/5 focus:ring-4 focus:ring-indigo-500/10 transition-all font-medium"
                                    />
                                </div>
                            } */}

                            {/* Empresa */}
                            <div className="space-y-2">
                                <div className="flex items-center gap-2 mb-1">
                                    <Building2 size={14} className="text-indigo-500" />
                                    <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Empresa Responsável</Label>
                                </div>
                                <Select 
                                    value={watch('empresa')} 
                                    onValueChange={(val) => setValue('empresa', val)}
                                >
                                    <SelectTrigger className="h-12 rounded-2xl bg-zinc-50 dark:bg-white/2 border-slate-200 dark:border-white/5">
                                        <SelectValue placeholder="Selecione a empresa" />
                                    </SelectTrigger>
                                    <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10 shadow-xl">
                                        <SelectItem value="B2B TRANSPORTES E LOGISTICAS LTDA">B2B TRANSPORTES E LOGISTICAS LTDA</SelectItem>
                                        <SelectItem value="PETY SERVICE LTDA">PETY SERVICE LTDA</SelectItem>
                                        <SelectItem value="RCS SERVICOS PROFISSIONAIS LTDA">RCS SERVICOS PROFISSIONAIS LTDA</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>

                            {/* Data Admissão — sempre visível */}
                            <div className={`grid gap-6 ${initialData ? 'grid-cols-2' : 'grid-cols-1'}`}>
                                <div className="space-y-2">
                                    <div className="flex items-center gap-2 mb-1">
                                        <Calendar size={14} className="text-indigo-500" />
                                        <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Data Admissão</Label>
                                    </div>
                                    <Input 
                                        type="date"
                                        {...register('data_admissao', { required: true })}
                                        className="h-12 rounded-2xl bg-zinc-50 dark:bg-white/2 border-slate-200 dark:border-white/5"
                                    />
                                </div>

                                {/* Status Global — apenas na edição */}
                                {/* {initialData && (
                                    <div className="space-y-2">
                                        <div className="flex items-center gap-2 mb-1">
                                            <Calendar size={14} className="text-indigo-500" />
                                            <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Status Global</Label>
                                        </div>
                                        <Select 
                                            value={watch('global_status')} 
                                            onValueChange={(val) => setValue('global_status', val)}
                                        >
                                            <SelectTrigger className="h-12 rounded-2xl bg-zinc-50 dark:bg-white/2 border-slate-200 dark:border-white/5">
                                                <SelectValue placeholder="Status" />
                                            </SelectTrigger>
                                            <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10 shadow-xl">
                                                <SelectItem value="Admissão">Admissão</SelectItem>
                                                <SelectItem value="Vencimento de Experiência">Vencimento Exp.</SelectItem>
                                                <SelectItem value="Prorrogação">Prorrogação</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </div>
                                )} */}

                                {/* Em criação: garante envio de 'Admissão' como valor do status */}
                                {!initialData && (
                                    <input type="hidden" {...register('global_status')} value="Admissão" />
                                )}
                            </div>

                            {/* Vencimentos */}
                            <div className="p-6 bg-zinc-50 dark:bg-white/2 rounded-[24px] border border-dashed border-slate-200 dark:border-white/10 space-y-6">
                                <div className="space-y-2">
                                    <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Vencimento Experiência</Label>
                                    <Input 
                                        type="date"
                                        {...register('vencimento_exp')}
                                        className="h-12 rounded-2xl bg-white dark:bg-[#0a0a0a] border-slate-200 dark:border-white/5 shadow-sm"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Prorrogação Experiência</Label>
                                    <Input 
                                        type="date"
                                        {...register('prorrogacao_exp')}
                                        className="h-12 rounded-2xl bg-white dark:bg-[#0a0a0a] border-slate-200 dark:border-white/5 shadow-sm"
                                    />
                                </div>
                            </div>

                        </form>

                        {/* Footer */}
                        <div className="p-8 border-t border-slate-100 dark:border-white/5">
                            <Button 
                                type="submit"
                                form="experience-contract-form"
                                className="w-full h-14 bg-indigo-600 hover:bg-indigo-700 text-white rounded-2xl font-bold uppercase tracking-[0.1em] text-xs shadow-xl shadow-indigo-500/20 group transition-all"
                            >
                                <span className="flex items-center gap-2">
                                    <Save size={18} />
                                    {initialData ? 'Salvar Alterações' : 'Criar Contrato'}
                                    <ChevronRight size={16} className="ml-1 group-hover:translate-x-1 transition-transform" />
                                </span>
                            </Button>
                        </div>
                    </motion.div>
                </>
            )}
        </AnimatePresence>
    );
};
