'use client';

import { CircleDollarSign, TriangleAlert } from 'lucide-react';
import { Alert, Button, Col, Progress, Row, Space, Statistic, Typography } from 'antd';
import Link from 'next/link';
import React from 'react';

import ContentCard from '@/components/layouts/ContentCard';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useTenantCurrency } from '@/hooks/useTenantCurrency';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { projetosProjetoCanonical } from '@/lib/routes/projetosProjetoCanonical';
import type { ResumoFinanceiroProjeto } from '../ProjetoFinancialCard/ProjetoFinancialCard';
import { queryKeys } from '@/lib/cache/queryKeys';
import { LoadingState } from '@/components/ui/LoadingState';

type ResumoFinanceiroHero = ResumoFinanceiroProjeto & {
    percentual_orcamento_utilizado?: number | null;
};

const { Text } = Typography;

export interface ProjetoFinanceiroHeroProps {
    projetoId: string;
}

/**
 * Hero financeiro no hub do projeto (TASK-PRJ-035 / R-02).
 */
export function ProjetoFinanceiroHero({ projetoId }: ProjetoFinanceiroHeroProps) {
    const { formatCurrency } = useTenantCurrency();
    const { data: resumo, isLoading } = useQueryCache<ResumoFinanceiroHero>({
        queryKey: queryKeys.projetos.resumoFinanceiroHero(projetoId),
        endpoint: API_ENDPOINTS.projetos.resumoFinanceiro(projetoId),
        enabled: Boolean(projetoId),
        staleTime: 2 * 60 * 1000,
    });

    return (
        <ContentCard
            title="Financeiro do projeto"
            icon={<CircleDollarSign size={18} aria-hidden />}
            style={{ marginBottom: 24 }}
        >
                {isLoading ? (
                    <div style={{ textAlign: 'center', padding: 24 }}>
                        <LoadingState label="Carregando resumo financeiro..." />
                    </div>
                ) : !resumo || (resumo.orcamento ?? 0) <= 0 ? (
                    <Space direction="vertical" size="small">
                        <Text type="secondary">
                            Ainda não há orçamento definido. Registe o budget para acompanhar desvios em tempo real.
                        </Text>
                        <Link href={projetosProjetoCanonical.projetoOrcamento(projetoId)}>
                            <Button type="primary" size="small">
                                Definir orçamento
                            </Button>
                        </Link>
                    </Space>
                ) : (
                    <>
                        <Row gutter={[16, 16]}>
                            <Col xs={24} sm={8}>
                                <Statistic
                                    title="Orçamento"
                                    value={resumo.orcamento}
                                    formatter={(value) => formatCurrency(Number(value))}
                                />
                            </Col>
                            <Col xs={24} sm={8}>
                                <Statistic
                                    title="Realizado"
                                    value={resumo.valor_realizado}
                                    formatter={(value) => formatCurrency(Number(value))}
                                    valueStyle={{ color: '#389e0d' }}
                                />
                            </Col>
                            <Col xs={24} sm={8}>
                                <Statistic
                                    title="Utilização"
                                    value={resumo.percentual_orcamento_utilizado ?? resumo.percentual_utilizado ?? 0}
                                    suffix="%"
                                    precision={1}
                                />
                            </Col>
                        </Row>
                        <div style={{ marginTop: 16 }}>
                            <Progress
                                percent={Math.min(
                                    resumo.percentual_orcamento_utilizado ?? resumo.percentual_utilizado ?? 0,
                                    100,
                                )}
                                status={resumo.status_orcamento === 'excedido' ? 'exception' : 'active'}
                                strokeColor={
                                    resumo.status_orcamento === 'excedido'
                                        ? '#ff4d4f'
                                        : resumo.status_orcamento === 'alerta'
                                          ? '#faad14'
                                          : '#52c41a'
                                }
                            />
                        </div>
                        {resumo.status_orcamento !== 'ok' && (
                            <Alert
                                style={{ marginTop: 16 }}
                                showIcon
                                icon={<TriangleAlert size={16} aria-hidden />}
                                type={resumo.status_orcamento === 'excedido' ? 'error' : 'warning'}
                                message={
                                    resumo.status_orcamento === 'excedido'
                                        ? 'Orçamento excedido'
                                        : 'Atenção ao desvio orçamentário'
                                }
                                description="Revise custos e entregas para evitar impacto na margem do projeto."
                            />
                        )}
                    </>
                )}
        </ContentCard>
    );
}
