import React from 'react';
import { 
  FileText,
  Search,
  Download,
  Receipt,
  History,
  TrendingUp,
  TrendingDown,
  Building2
} from 'lucide-react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { cn } from '@/lib/utils';
import { Filter } from 'lucide-react';
import ExcelTable from '../../components/ExcelTable';
import { formatDate, formatCurrency } from '../../utils/dateUtils';
import { parseDateInfo } from '@/utils/dateUtils';
import { StatementRow } from '../../components/StatementRow';
import { useStatementRefData } from '../../hooks/useStatementRefData';
import { CategorizacaoDialog } from '../../components/CategorizacaoDialog';
import { TransactionDetailModal } from '../../components/TransactionDetailModal';

const MESES = ['', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
const ANOS = Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - 2 + i);

export function ExtratoCompletoView({ state, actions }) {
    const [searchTerm, setSearchTerm] = React.useState('');
    const [filterType, setFilterType] = React.useState('todos'); // 'todos' | 'C' | 'D'
    const [filterMonth, setFilterMonth] = React.useState(String(new Date().getMonth() + 1));
    const [filterYear, setFilterYear] = React.useState(String(new Date().getFullYear()));
    const [transacaoSelecionada, setTransacaoSelecionada] = React.useState(null);
    const [isDialogOpen, setIsDialogOpen] = React.useState(false);
    const [isDetailOpen, setIsDetailOpen] = React.useState(false);

    const { 
        extratoCompleto = [], 
        caixas = [], 
        isLoading = false 
    } = state || {};

    const { getCategoryName, getRuleName } = useStatementRefData();

    // Filtragem local multi-critério
    const filteredExtrato = React.useMemo(() => {
        if (!extratoCompleto || !Array.isArray(extratoCompleto)) return [];
        
        return extratoCompleto.filter(t => {
            // 1. Busca por termo
            const searchMatch = !searchTerm || 
                t.descricao?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                t.beneficiario_pagador?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                t.categoria?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                t.titulo?.toLowerCase().includes(searchTerm.toLowerCase());
            
            if (!searchMatch) return false;

            // 2. Filtro de Tipo (Entrada/Saída)
            if (filterType !== 'todos') {
                if (t.tipoOperacao !== filterType) return false;
            }

            // 3. Filtro de Mês/Ano (Data)
            if (filterMonth !== 'todos' || filterYear !== 'todos') {
                const dateRaw = t.dataEntrada || t.data;
                if (!dateRaw) return false;
                
                const { year, month } = parseDateInfo(dateRaw);
                const dateMonth = String(month);
                const dateYear = String(year);

                if (filterMonth !== 'todos' && dateMonth !== filterMonth) return false;
                if (filterYear !== 'todos' && dateYear !== filterYear) return false;
            }

            return true;
        });
    }, [extratoCompleto, searchTerm, filterType, filterMonth, filterYear]);

    // Resumo financeiro do período filtrado
    const resumo = React.useMemo(() => {
        return filteredExtrato.reduce((acc, t) => {
            const valor = Number(t.valor) || 0;
            const isC = t.tipoOperacao ? t.tipoOperacao === 'C' : valor > 0;
            
            if (isC) {
                acc.creditos += Math.abs(valor);
                acc.total += Math.abs(valor);
            } else {
                acc.debitos += Math.abs(valor);
                acc.total -= Math.abs(valor);
            }
            return acc;
        }, { creditos: 0, debitos: 0, total: 0 });
    }, [filteredExtrato]);

    return (
        <div className="animate-in fade-in duration-700 space-y-6">


            <Card className="bg-white dark:bg-[#1e293b]/40 backdrop-blur-md border-slate-200 dark:border-slate-800 shadow-xl rounded-lg overflow-hidden">
                <CardHeader className="py-4 px-4 sm:px-6 border-b border-slate-200 dark:border-slate-800/50">
                    <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                        <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-xl bg-blue-500/10 flex items-center justify-center border border-blue-500/20 shrink-0">
                                <History className="w-5 h-5 text-blue-500" />
                            </div>
                            <div>
                                <h3 className="font-bold text-slate-900 dark:text-white flex items-center gap-2 flex-wrap text-base sm:text-lg">
                                    Extrato Completo
                                    <Badge variant="outline" className="text-[10px] border-slate-300 dark:border-slate-700 text-slate-600 dark:text-slate-400 bg-slate-50 dark:bg-slate-900/50">
                                        {filteredExtrato.length} LANÇAMENTOS
                                    </Badge>
                                </h3>
                                
                                <div className="hidden lg:flex items-center gap-3">
                                    <div className="h-4 w-px bg-slate-200 dark:bg-slate-800 mr-2" />
                                    <div className="flex items-center gap-1.5 p-1 bg-slate-100/50 dark:bg-slate-900/50 rounded-lg">
                                        <Button 
                                            variant="ghost" 
                                            size="sm" 
                                            onClick={() => setFilterType('todos')}
                                            className={cn("h-7 px-3 text-[10px] font-bold uppercase", filterType === 'todos' ? "bg-white dark:bg-slate-800 shadow-sm text-slate-900 dark:text-white" : "text-slate-500")}
                                        >Todos</Button>
                                        <Button 
                                            variant="ghost" 
                                            size="sm" 
                                            onClick={() => setFilterType('C')}
                                            className={cn("h-7 px-3 text-[10px] font-bold uppercase", filterType === 'C' ? "bg-white dark:bg-slate-800 text-emerald-600 dark:text-emerald-400 shadow-sm" : "text-slate-500")}
                                        >Créditos</Button>
                                        <Button 
                                            variant="ghost" 
                                            size="sm" 
                                            onClick={() => setFilterType('D')}
                                            className={cn("h-7 px-3 text-[10px] font-bold uppercase", filterType === 'D' ? "bg-white dark:bg-slate-800 text-rose-600 dark:text-rose-400 shadow-sm" : "text-slate-500")}
                                        >Débitos</Button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto">
                            <div className="flex items-center gap-2">
                                <Select value={filterMonth} onValueChange={setFilterMonth}>
                                    <SelectTrigger className="w-[110px] h-9 bg-white dark:bg-slate-900/80 text-xs font-bold border-slate-200 dark:border-slate-800">
                                        <SelectValue placeholder="Mês" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="todos">Todos Meses</SelectItem>
                                        {MESES.map((m, i) => i > 0 && <SelectItem key={i} value={String(i)}>{m}</SelectItem>)}
                                    </SelectContent>
                                </Select>
                                <Select value={filterYear} onValueChange={setFilterYear}>
                                    <SelectTrigger className="w-[90px] h-9 bg-white dark:bg-slate-900/80 text-xs font-bold border-slate-200 dark:border-slate-800">
                                        <SelectValue placeholder="Ano" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="todos">Todos Anos</SelectItem>
                                        {ANOS.map(a => <SelectItem key={a} value={String(a)}>{a}</SelectItem>)}
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="relative flex-1 sm:flex-initial">
                                <Search className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                                <Input 
                                    placeholder="Buscar no extrato..." 
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    className="bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-800 pl-9 h-9 text-xs w-full sm:w-64 text-slate-900 dark:text-white"
                                />
                            </div>
                            <Button 
                                variant="outline" 
                                size="sm" 
                                className="h-9 border-slate-200 dark:border-slate-700"
                                onClick={() => actions?.exportarPDF?.()}
                            >
                                <Download className="w-4 h-4 mr-2" />
                                Exportar
                            </Button>
                        </div>
                    </div>
                </CardHeader>
                <CardContent className="p-0">
                    <div className="h-[600px]">
                        <div className="divide-y divide-slate-100 dark:divide-slate-800 overflow-auto h-[600px] custom-scrollbar">
                            {filteredExtrato.length > 0 ? (
                                filteredExtrato.map((row, index) => (
                                    <StatementRow
                                        key={row.id || row.idextrato || index}
                                        transaction={row}
                                        categoryName={getCategoryName(row.categoria)}
                                        ruleName={getRuleName(row.regra)}
                                        onClick={(t) => {
                                            console.log('[ExtratoCompletoView] Clique na transação:', t);
                                            console.log('[ExtratoCompletoView] Abrindo modal de detalhes...');
                                            setTransacaoSelecionada(t);
                                            setIsDetailOpen(true);
                                        }}
                                        showCategory={true}
                                        showStatus={false}
                                        showBeneficiary={true}
                                    />
                                ))
                            ) : (
                                <div className="flex flex-col items-center justify-center h-full text-slate-500">
                                    <FileText className="h-12 w-12 mb-4 opacity-20" />
                                    <p>Nenhum lançamento encontrado</p>
                                </div>
                            )}
                        </div>
                    </div>
                </CardContent>
            </Card>

            <CategorizacaoDialog
                transacao={transacaoSelecionada}
                isOpen={isDialogOpen}
                onOpenChange={setIsDialogOpen}
                categorias={state?.categorias}
                caixas={state?.caixas}
                actions={actions}
            />

            <TransactionDetailModal
                transaction={transacaoSelecionada}
                open={isDetailOpen}
                onOpenChange={setIsDetailOpen}
                onEditTransaction={(t) => {
                    setTransacaoSelecionada(t);
                    setIsDialogOpen(true);
                }}
                categorias={state?.categorias}
                caixas={state?.caixas}
            />
        </div>
    );
};
