'use client';

import { CircleDollarSign, Clock, TrendingDown, TrendingUp, TriangleAlert } from 'lucide-react';
import {
    Alert,
    Card,
    Col,
    Empty,
    Progress,
    Row,
    Space,
    Typography,
} from 'antd';

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

const { Title, Text } = Typography;

export interface BudgetForecastProps {
    projetoId: number | string;
}

export interface ForecastData {
    projeto_id: number;
    periodo: {
        inicio: string;
        fim: string;
        dias_restantes: number;
    };
    custos: {
        realizado: number;
        planejado: number;
        restante_projetado: number;
    };
    forecast: {
        base: number;
        otimista: number;
        pessimista: number;
        realista: number;
    };
    indicadores: {
        progresso_percentual: number;
        taxa_consumo_tempo: number;
        horas_realizadas: number;
        data_esgotamento: string | null;
    };
}

export function BudgetForecast({ projetoId }: BudgetForecastProps) {
    const { data: forecastData, isLoading } = useQueryCache<ForecastData>({
        queryKey: queryKeys.projetos.forecast(projetoId),
        endpoint: API_ENDPOINTS.projetos.forecast(projetoId),
        enabled: !!projetoId,
        staleTime: 2 * 60 * 1000, // 2 minutos
        gcTime: 10 * 60 * 1000,
    });

    if (isLoading) {
        return (
            <div style={{ textAlign: 'center', padding: '40px' }}>
                <LoadingState size="large" label="Calculando forecast..." />
            </div>
        );
    }

    if (!forecastData) {
        return <Empty description="Nenhum dado de forecast disponível" />;
    }

    const { custos, forecast, indicadores, periodo } = forecastData;

    return (
        <div>
            <Title level={5} style={{ marginBottom: 24 }}>
                <TrendingUp style={{ marginRight: 8 }} />
                Forecast de Custos
            </Title>

            <Row gutter={[16, 16]}>
                <Col xs={24} sm={12} md={8}>
                    <FinancialCard
                        title="Custo Realizado"
                        value={custos.realizado}
                        subtitle="Até o momento"
                        icon={<CircleDollarSign />}
                    />
                </Col>
                <Col xs={24} sm={12} md={8}>
                    <FinancialCard
                        title="Custo Planejado"
                        value={custos.planejado}
                        subtitle="Estimativa inicial"
                        icon={<CircleDollarSign />}
                    />
                </Col>
                <Col xs={24} sm={12} md={8}>
                    <FinancialCard
                        title="Restante Projetado"
                        value={custos.restante_projetado}
                        subtitle="Custos futuros estimados"
                        icon={<CircleDollarSign />}
                        status={custos.restante_projetado > custos.realizado ? 'atencao' : 'ok'}
                    />
                </Col>
            </Row>

            <Card title="Cenários de Forecast" style={{ marginTop: 24 }}>
                <Row gutter={[16, 16]}>
                    <Col xs={24} sm={8}>
                        <FinancialCard
                            title="Cenário Otimista"
                            value={forecast.otimista}
                            subtitle="Melhor caso"
                            size="small"
                            color="#52c41a"
                            icon={<TrendingDown />}
                        />
                    </Col>
                    <Col xs={24} sm={8}>
                        <FinancialCard
                            title="Cenário Realista"
                            value={forecast.realista}
                            subtitle="Mais provável"
                            size="small"
                            color="#1890ff"
                            icon={<TrendingUp />}
                        />
                    </Col>
                    <Col xs={24} sm={8}>
                        <FinancialCard
                            title="Cenário Pessimista"
                            value={forecast.pessimista}
                            subtitle="Pior caso"
                            size="small"
                            color="#ff4d4f"
                            icon={<TriangleAlert />}
                        />
                    </Col>
                </Row>
            </Card>

            <Card title="Indicadores" style={{ marginTop: 24 }}>
                <Space direction="vertical" style={{ width: '100%' }} size="large">
                    <div>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                            <Text>Progresso do Projeto</Text>
                            <Text strong>{indicadores.progresso_percentual.toFixed(1)}%</Text>
                        </div>
                        <Progress percent={indicadores.progresso_percentual} />
                    </div>

                    <div>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                            <Text>Taxa de Consumo de Tempo</Text>
                            <Text strong>{indicadores.taxa_consumo_tempo.toFixed(1)}%</Text>
                        </div>
                        <Progress 
                            percent={indicadores.taxa_consumo_tempo} 
                            status={indicadores.taxa_consumo_tempo > indicadores.progresso_percentual ? 'exception' : 'normal'}
                        />
                    </div>

                    <div>
                        <Space>
                            <Clock />
                            <Text>Horas Realizadas: <strong>{indicadores.horas_realizadas.toFixed(1)}h</strong></Text>
                        </Space>
                    </div>

                    {indicadores.data_esgotamento && (
                        <Alert
                            message="Data de Esgotamento do Orçamento"
                            description={`Com base na tendência atual, o orçamento pode se esgotar em ${indicadores.data_esgotamento}`}
                            type="warning"
                            showIcon
                        />
                    )}

                    <div>
                        <Text type="secondary">
                            Período: {new Date(periodo.inicio).toLocaleDateString('pt-BR')} até {new Date(periodo.fim).toLocaleDateString('pt-BR')}
                            {' '}({periodo.dias_restantes} dias restantes)
                        </Text>
                    </div>
                </Space>
            </Card>
        </div>
    );
}

