'use client';

import { CheckCircle2, CircleDollarSign, TrendingDown, TrendingUp, TriangleAlert } from 'lucide-react';
import {
    Alert,
    Card,
    Col,
    Progress,
    Row,
    Statistic,
    Tag,
    Tooltip,
} from 'antd';

import { ICON_SIZE_MD } from '@/components/icons';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';

export interface ProjetoFinancialCardProps {
    projetoId: number | string;
    orcamento?: number;
    valorRealizado?: number;
    showDetails?: boolean;
}

export interface ResumoFinanceiroProjeto {
    projeto_id: number;
    orcamento: number;
    valor_realizado: number;
    custo_total: number;
    percentual_utilizado: number;
    saldo: number;
    roi: number;
    status_orcamento: 'ok' | 'atencao' | 'alerta' | 'excedido';
    custo_por_status: Record<string, { total: number; quantidade: number }>;
}

export function ProjetoFinancialCard({ 
    projetoId, 
    orcamento: orcamentoProp, 
    valorRealizado: valorRealizadoProp,
    showDetails = false 
}: ProjetoFinancialCardProps) {
    const { data: resumoData } = useQueryCache<ResumoFinanceiroProjeto>({
        queryKey: queryKeys.projetos.resumoFinanceiroCard(projetoId),
        endpoint: API_ENDPOINTS.projetos.resumoFinanceiro(projetoId),
        enabled: !!projetoId && showDetails,
        staleTime: 2 * 60 * 1000, // 2 minutos
    });

    // Usar dados da prop ou do cache
    const orcamento = orcamentoProp ?? resumoData?.orcamento ?? 0;
    const valorRealizado = valorRealizadoProp ?? resumoData?.valor_realizado ?? 0;
    const percentualUtilizado = resumoData?.percentual_utilizado ?? (orcamento > 0 ? (valorRealizado / orcamento) * 100 : 0);
    const saldo = orcamento - valorRealizado;
    const roi = resumoData?.roi ?? (orcamento > 0 ? ((valorRealizado - orcamento) / orcamento) * 100 : 0);
    const statusOrcamento = resumoData?.status_orcamento ?? 
        (percentualUtilizado > 100 ? 'excedido' : 
         percentualUtilizado > 90 ? 'alerta' : 
         percentualUtilizado > 75 ? 'atencao' : 'ok');

    if (!showDetails && (!orcamento || orcamento === 0)) {
        return null;
    }

    const getStatusColor = () => {
        switch (statusOrcamento) {
            case 'excedido':
                return '#ff4d4f';
            case 'alerta':
                return '#faad14';
            case 'atencao':
                return '#fa8c16';
            default:
                return '#52c41a';
        }
    };

    const getStatusIcon = () => {
        switch (statusOrcamento) {
            case 'excedido':
                return <TriangleAlert style={{ color: '#ff4d4f' }} />;
            case 'alerta':
                return <TriangleAlert style={{ color: '#faad14' }} />;
            case 'atencao':
                return <TriangleAlert style={{ color: '#fa8c16' }} />;
            default:
                return <CheckCircle2 style={{ color: '#52c41a' }} />;
        }
    };

    if (!showDetails) {
        // Versão compacta para cards
        return (
            <div style={{ marginTop: '8px', padding: '8px', background: '#f5f5f5', borderRadius: '4px' }}>
                <Row gutter={8} align="middle">
                    <Col flex="auto">
                        <div style={{ fontSize: '12px', color: '#666' }}>
                            <CircleDollarSign style={{ marginRight: '4px' }} />
                            Orçamento: R$ {orcamento.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                        </div>
                        {valorRealizado > 0 && (
                            <div style={{ fontSize: '11px', color: '#999', marginTop: '4px' }}>
                                Realizado: R$ {valorRealizado.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                            </div>
                        )}
                    </Col>
                    {roi !== 0 && (
                        <Col>
                            <Tag color={roi >= 0 ? 'green' : 'red'}>
                                ROI: {roi >= 0 ? '+' : ''}{roi.toFixed(1)}%
                            </Tag>
                        </Col>
                    )}
                </Row>
                {orcamento > 0 && (
                    <Progress
                        percent={Math.min(percentualUtilizado, 100)}
                        size="small"
                        strokeColor={getStatusColor()}
                        showInfo={false}
                        style={{ marginTop: '8px' }}
                    />
                )}
            </div>
        );
    }

    // Versão detalhada
    return (
        <Card size="small" style={{ marginTop: '16px' }}>
            <Row gutter={[16, 16]}>
                <Col xs={24} sm={12} md={6}>
                    <Statistic
                        title="Orçamento"
                        value={orcamento}
                        prefix={<CircleDollarSign />}
                        precision={2}
                        valueStyle={{ color: '#1890ff' }}
                    />
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Statistic
                        title="Valor Realizado"
                        value={valorRealizado}
                        prefix={<CircleDollarSign />}
                        precision={2}
                        valueStyle={{ color: '#52c41a' }}
                    />
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Statistic
                        title="Saldo"
                        value={saldo}
                        prefix={<CircleDollarSign />}
                        precision={2}
                        valueStyle={{ color: saldo >= 0 ? '#52c41a' : '#ff4d4f' }}
                    />
                </Col>
                <Col xs={24} sm={12} md={6}>
                    <Statistic
                        title="ROI"
                        value={roi}
                        suffix="%"
                        prefix={roi >= 0 ? <TrendingUp /> : <TrendingDown />}
                        valueStyle={{ color: roi >= 0 ? '#52c41a' : '#ff4d4f' }}
                        precision={2}
                    />
                </Col>
            </Row>

            {orcamento > 0 && (
                <>
                    <div style={{ marginTop: '16px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                            <span style={{ fontSize: '12px', color: '#666' }}>Utilização do Orçamento</span>
                            <span style={{ fontSize: '12px', fontWeight: 'bold', color: getStatusColor() }}>
                                {percentualUtilizado.toFixed(1)}%
                            </span>
                        </div>
                        <Progress
                            percent={Math.min(percentualUtilizado, 100)}
                            strokeColor={getStatusColor()}
                            status={statusOrcamento === 'excedido' ? 'exception' : 'active'}
                        />
                    </div>

                    {statusOrcamento !== 'ok' && (
                        <Alert
                            message={
                                statusOrcamento === 'excedido' 
                                    ? 'Orçamento excedido!' 
                                    : statusOrcamento === 'alerta'
                                    ? 'Orçamento próximo do limite'
                                    : 'Atenção ao orçamento'
                            }
                            type={statusOrcamento === 'excedido' ? 'error' : 'warning'}
                            icon={getStatusIcon()}
                            style={{ marginTop: '16px' }}
                            showIcon
                        />
                    )}
                </>
            )}

            {resumoData?.custo_por_status && Object.keys(resumoData.custo_por_status).length > 0 && (
                <div style={{ marginTop: '16px' }}>
                    <div style={{ fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>Custo por Status</div>
                    <Row gutter={[8, 8]}>
                        {Object.entries(resumoData.custo_por_status).map(([status, dados]) => (
                            <Col key={status} span={12}>
                                <Tooltip title={`${dados.quantidade} projeto(s) neste status`}>
                                    <div style={{ 
                                        padding: '8px', 
                                        background: '#f5f5f5', 
                                        borderRadius: '4px',
                                        fontSize: '11px'
                                    }}>
                                        <div style={{ fontWeight: 'bold' }}>{status}</div>
                                        <div style={{ color: '#666' }}>
                                            R$ {dados.total.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                                        </div>
                                    </div>
                                </Tooltip>
                            </Col>
                        ))}
                    </Row>
                </div>
            )}
        </Card>
    );
}

