import React, { useEffect, useState } from 'react';
import { 
    LayoutDashboard, 
    Plus, 
    LayoutGrid, 
    Table,
    Search,
    RefreshCw,
    Briefcase
} from 'lucide-react';
import { useExperienceContracts } from '../hooks/useExperienceContracts';
import { ExperienceContractKanban } from '../components/ExperienceContractKanban';
import { ExperienceContractTable } from '../components/ExperienceContractTable';
import { ExperienceContractDashboard } from '../components/ExperienceContractDashboard';
import { ExperienceContractFormSidebar } from '../components/ExperienceContractFormSidebar';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { 
    Tabs, 
    TabsList, 
    TabsTrigger 
} from '@/components/ui/tabs';

/**
 * View Principal de Gestão de Contratos de Experiência do RH.
 * Integra Kanban, Tabela e Dashboard em uma interface unificada.
 */
export const ContratosExperienciaView = () => {
    const {
        contracts,
        stats,
        loading,
        viewMode,
        setViewMode,
        displayMode,
        setDisplayMode,
        filters,
        setFilters,
        fetchContracts,
        fetchStatistics,
        handleCreateContract,
        handleUpdateContract,
        handleMoveCard
    } = useExperienceContracts();

    const [isSidebarOpen, setIsSidebarOpen] = useState(false);
    const [selectedContract, setSelectedContract] = useState(null);

    useEffect(() => {
        fetchContracts();
    }, [fetchContracts]);

    const handleEdit = (item) => {
        setSelectedContract(item);
        setIsSidebarOpen(true);
    };

    const handleNew = () => {
        setSelectedContract(null);
        setIsSidebarOpen(true);
    };

    const onFormSubmit = async (data) => {
        let success = false;
        if (selectedContract) {
            // Edit
            success = await handleUpdateContract({
                idcontrato_rh: selectedContract.idcontrato_rh,
                ...data
            });
        } else {
            // Create
            success = await handleCreateContract(data);
        }

        if (success) {
            setIsSidebarOpen(false);
        }
    };

    return (
        <div className="theme-rh flex-1 flex flex-col h-full w-full overflow-hidden bg-slate-50/50 dark:bg-[#0a0a0a] p-4 sm:p-6 lg:p-10 space-y-8">
            
            {/* Header / Top Bar */}
            <div className="flex flex-col xl:flex-row xl:items-center justify-between gap-8">
                <div className="space-y-2">
                    <div className="flex items-center gap-4">
                        <div className="p-3 bg-indigo-500/10 rounded-2xl shadow-inner border border-indigo-500/5">
                            <Briefcase className="text-indigo-500" size={24} />
                        </div>
                        <h1 className="text-3xl md:text-5xl font-bold text-slate-800 dark:text-white tracking-tighter leading-none">
                            Contratos de <span className="text-indigo-500">Experiência</span>
                        </h1>
                    </div>
                    <p className="text-slate-400 dark:text-slate-500 text-sm md:text-base font-medium italic opacity-80 pl-1">
                        Gerencie registros e acompanhe métricas de admissão
                    </p>
                </div>

                <div className="flex flex-wrap items-center gap-4">
                    {/* View Selector (Registros vs Dashboards) */}
                    <Tabs value={viewMode} onValueChange={setViewMode} className="bg-white dark:bg-white/2 p-1.5 rounded-[24px] border border-slate-200 dark:border-white/5 shadow-sm">
                        <TabsList className="bg-transparent border-none gap-2">
                            <TabsTrigger 
                                value="registros" 
                                className="px-6 py-2.5 rounded-[20px] text-[10px] font-bold uppercase tracking-wider data-[state=active]:bg-indigo-500 data-[state=active]:text-white transition-all shadow-none"
                            >
                                <LayoutGrid size={14} className="mr-2" /> Registros
                            </TabsTrigger>
                            <TabsTrigger 
                                value="dashboards" 
                                className="px-6 py-2.5 rounded-[20px] text-[10px] font-bold uppercase tracking-wider data-[state=active]:bg-indigo-500 data-[state=active]:text-white transition-all shadow-none"
                            >
                                <LayoutDashboard size={14} className="mr-2" /> Dashboards
                            </TabsTrigger>
                        </TabsList>
                    </Tabs>

                    {/* Refresh Button */}
                    <Button 
                        onClick={fetchContracts}
                        disabled={loading}
                        variant="outline"
                        className="h-12 w-12 rounded-2xl border-slate-200 dark:border-white/5 bg-white dark:bg-white/2 hover:scale-105 transition-transform"
                    >
                        <RefreshCw size={18} className={`${loading ? 'animate-spin' : ''} text-slate-500`} />
                    </Button>

                    {/* Add Button */}
                    {/* <Button 
                        onClick={handleNew}
                        className="h-12 px-8 bg-indigo-600 hover:bg-indigo-700 text-white rounded-2xl font-bold uppercase tracking-[0.1em] text-[10px] shadow-xl shadow-indigo-500/20 active:scale-95 transition-all"
                    >
                        <Plus size={18} className="mr-2" /> Novo Contrato
                    </Button> */}
                </div>
            </div>

            {/* Filter Bar / Mode Switcher (Unicamente para visualização de Registros) */}
            {viewMode === 'registros' && (
                <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-6 animate-in slide-in-from-top-4 duration-500">
                    <div className="relative group max-w-md w-full">
                        <Search size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-indigo-500 transition-colors" />
                        <Input 
                            value={filters.search}
                            onChange={(e) => setFilters({ search: e.target.value })}
                            placeholder="Buscar colaborador por nome ou ID..." 
                            className="pl-12 h-14 bg-white dark:bg-white/2 border-slate-200 dark:border-white/5 rounded-[24px] text-xs focus:outline-none focus:ring-4 focus:ring-indigo-500/10 transition-all font-semibold shadow-sm"
                        />
                    </div>

                    <div className="flex items-center gap-1.5 p-1.5 bg-slate-100 dark:bg-white/2 rounded-[24px] border border-slate-200/50 dark:border-white/5 shadow-inner">
                        <button 
                            onClick={() => setDisplayMode('kanban')}
                            className={`p-3 rounded-[20px] transition-all ${displayMode === 'kanban' ? 'bg-white dark:bg-slate-700 shadow-lg text-indigo-500 dark:text-white' : 'text-slate-400 hover:text-slate-600 dark:hover:text-slate-300'}`}
                            title="Visualização Kanban"
                        >
                            <LayoutGrid size={18} />
                        </button>
                        <button 
                            onClick={() => setDisplayMode('tabela')}
                            className={`p-3 rounded-[20px] transition-all ${displayMode === 'tabela' ? 'bg-white dark:bg-slate-700 shadow-lg text-indigo-500 dark:text-white' : 'text-slate-400 hover:text-slate-600 dark:hover:text-slate-300'}`}
                            title="Visualização em Tabela"
                        >
                            <Table size={18} />
                        </button>
                    </div>
                </div>
            )}

            {/* Main Content Area */}
            <div className="flex-1 flex flex-col min-h-0">
                {viewMode === 'registros' ? (
                    displayMode === 'kanban' ? (
                        <div className="flex-1 p-2 overflow-hidden">
                            <ExperienceContractKanban 
                                contracts={contracts}
                                onCardMove={handleMoveCard}
                                onCardClick={handleEdit}
                                loading={loading}
                            />
                        </div>
                    ) : (
                        <div className="flex-1 p-2 overflow-hidden flex flex-col min-h-0">
                            <ExperienceContractTable 
                                contracts={contracts}
                                loading={loading}
                                onEdit={handleEdit}
                            />
                        </div>
                    )
                ) : (
                    <ExperienceContractDashboard 
                        stats={stats}
                        fetchStatistics={fetchStatistics}
                        filters={filters}
                        setFilters={setFilters}
                    />
                )}
            </div>

            {/* Sidebar de Formulário */}
            <ExperienceContractFormSidebar 
                isOpen={isSidebarOpen}
                onClose={() => setIsSidebarOpen(false)}
                onSubmit={onFormSubmit}
                initialData={selectedContract}
            />
        </div>
    );
};
