import React, { useEffect, useState, useMemo } from 'react';
import { useGestaoFaltasAtestados } from '../hooks/useGestaoFaltasAtestados';
import ExcelTable from '../components/ExcelTable';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { 
  ClipboardList, 
  Search, 
  RefreshCw,
  AlertTriangle,
  FileText,
  UserX
} from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

/**
 * View de Gestão Completa de Faltas, Atestados e Afastamentos
 */
export const GestaoFaltasAtestadosView = () => {
  const {
    dados,
    faltas,
    atestados,
    afastamentos,
    loading,
    filters,
    fetchGestaoCompleta,
    setFilters
  } = useGestaoFaltasAtestados();

  const [tipoVisualizacao, setTipoVisualizacao] = useState('todos'); // 'todos', 'faltas', 'atestados', 'afastamentos'

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

  const columns = [
    { field: 'id', header: 'ID', width: 80 },
    { field: 'tipo', header: 'Tipo', width: 120, render: (row) => {
      const tipoColors = {
        'Falta': 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300',
        'Atestado': 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300',
        'Afastamento': 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300'
      };
      return (
        <span className={`px-2 py-1 rounded-xl text-[clamp(1rem,1.1vw,1.0625rem)] font-medium ${tipoColors[row.tipo] || 'bg-slate-100'}`}>
          {row.tipo}
        </span>
      );
    }},
    { field: 'nome', header: 'Nome', width: 250 },
    { field: 'cargo', header: 'Cargo', width: 180 },
    { field: 'base', header: 'Base', width: 120 },
    { field: 'data', header: 'Data', width: 120, render: (row) => (
      <span className="text-[clamp(1rem,1.1vw,1.0625rem)] font-mono">
        {row.data ? new Date(row.data).toLocaleDateString('pt-BR') : '-'}
      </span>
    )},
    { field: 'data_fim', header: 'Data Fim', width: 120, render: (row) => (
      <span className="text-[clamp(1rem,1.1vw,1.0625rem)] font-mono">
        {row.data_fim ? new Date(row.data_fim).toLocaleDateString('pt-BR') : '-'}
      </span>
    )},
    { field: 'tipo_detalhe', header: 'Detalhe', width: 150 },
    { field: 'dias', header: 'Dias', width: 80 },
    { field: 'quantidade', header: 'Qtd', width: 80 },
    { field: 'status', header: 'Status', width: 100 }
  ];

  const stats = [
    {
      label: 'Total de Registros',
      value: dados.length,
      icon: ClipboardList,
      color: 'bg-indigo-500/10 text-indigo-500'
    },
    {
      label: 'Faltas',
      value: faltas.length,
      icon: AlertTriangle,
      color: 'bg-rose-500/10 text-rose-500'
    },
    {
      label: 'Atestados',
      value: atestados.length,
      icon: FileText,
      color: 'bg-blue-500/10 text-blue-500'
    },
    {
      label: 'Afastamentos',
      value: afastamentos.length,
      icon: UserX,
      color: 'bg-amber-500/10 text-amber-500'
    }
  ];

  const dadosFiltrados = useMemo(() => {
    let result = [...dados];
    
    // Filtro por tipo de visualização
    if (tipoVisualizacao === 'faltas') {
      result = faltas;
    } else if (tipoVisualizacao === 'atestados') {
      result = atestados;
    } else if (tipoVisualizacao === 'afastamentos') {
      result = afastamentos;
    }
    
    if (filters.search) {
      const searchLower = filters.search.toLowerCase();
      result = result.filter(d => 
        (d.nome || '').toLowerCase().includes(searchLower) ||
        (d.cargo || '').toLowerCase().includes(searchLower)
      );
    }
    
    if (filters.tipo) {
      result = result.filter(d => d.tipo === filters.tipo);
    }
    
    if (filters.status) {
      result = result.filter(d => d.status === filters.status);
    }
    
    return result;
  }, [dados, faltas, atestados, afastamentos, tipoVisualizacao, filters]);

  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 md:p-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
        <div className="space-y-1">
          <div className="flex items-center gap-3">
            <div className="p-2 sm:p-3 bg-indigo-500/10 rounded-xl">
              <ClipboardList className="text-indigo-500" size={24} />
            </div>
            <h1 className="text-[clamp(1.5rem,3vw,2.25rem)] font-semibold text-slate-800 dark:text-white tracking-tight">
              Gestão de Faltas, Atestados e Afastamentos
            </h1>
          </div>
          <p className="text-slate-500 text-[clamp(1rem,1.1vw,1.0625rem)] font-normal ml-1">
            Visão consolidada de todas as ocorrências
          </p>
        </div>
        
        <Button 
          onClick={() => fetchGestaoCompleta()}
          disabled={loading}
          variant="outline"
          size="sm"
        >
          <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
        </Button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        {stats.map((stat, idx) => {
          const Icon = stat.icon;
          return (
            <Card key={idx} className="rounded-2xl border-slate-200 dark:border-white/5 overflow-hidden">
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-[clamp(1.5rem,2.8vw,2.25rem)] font-semibold text-slate-800 dark:text-white">
                      {stat.value}
                    </p>
                    <p className="text-[clamp(1rem,1.1vw,1.0625rem)] text-slate-500 font-medium uppercase tracking-wider mt-1">
                      {stat.label}
                    </p>
                  </div>
                  <div className={`p-3 rounded-xl ${stat.color}`}>
                    <Icon size={20} />
                  </div>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>

      {/* Filtros */}
      <Card className="mb-6 border-slate-200 dark:border-white/5">
        <CardContent className="p-4">
          <div className="flex flex-col sm:flex-row gap-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
                <Input
                  placeholder="Buscar por nome ou cargo..."
                  value={filters.search || ''}
                  onChange={(e) => setFilters({ search: e.target.value })}
                  className="pl-10"
                />
              </div>
            </div>
            <Select 
              value={tipoVisualizacao} 
              onValueChange={setTipoVisualizacao}
            >
              <SelectTrigger className="w-full sm:w-[200px] rounded-xl">
                <SelectValue placeholder="Tipo" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="todos">Todos</SelectItem>
                <SelectItem value="faltas">Faltas</SelectItem>
                <SelectItem value="atestados">Atestados</SelectItem>
                <SelectItem value="afastamentos">Afastamentos</SelectItem>
              </SelectContent>
            </Select>
            <Select 
              value={filters.tipo || undefined} 
              onValueChange={(value) => setFilters({ tipo: value || '' })}
            >
              <SelectTrigger className="w-full sm:w-[200px] rounded-xl">
                <SelectValue placeholder="Tipo de Registro" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="Falta">Falta</SelectItem>
                <SelectItem value="Atestado">Atestado</SelectItem>
                <SelectItem value="Afastamento">Afastamento</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* Tabela */}
      <Card className="flex-1 flex flex-col overflow-hidden rounded-2xl border-slate-200 dark:border-white/5">
        <CardHeader className="border-b border-slate-200 dark:border-white/5">
          <CardTitle className="text-[clamp(1.125rem,2vw,1.5rem)] font-semibold">
            Registros ({dadosFiltrados.length})
          </CardTitle>
        </CardHeader>
        <CardContent className="flex-1 overflow-hidden p-0">
          <ExcelTable
            data={dadosFiltrados}
            columns={columns}
            loading={loading}
            pageSize={50}
          />
        </CardContent>
      </Card>
    </div>
  );
};
