'use client';

import { ArrowDown, ArrowUp, Bot, CheckCircle2, CircleDollarSign, CirclePlay, Clock, CreditCard, GitBranch, Percent, XCircle } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useMemo } from 'react';
import { Row, Col, Alert, Tag, Button, Empty, Collapse } from 'antd';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useIsMobile } from '@/hooks/useIsMobile';
import { queryKeys } from '@/lib/cache/queryKeys';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { LazyPieChart, LazyBarChart } from '@/components/lazy';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import { DetailPageLayout } from '@/components/layouts/DetailPageLayout';
import ContentCard from '@/components/layouts/ContentCard';
import MetricsGrid from '@/components/layouts/MetricsGrid';
import MetricCard from '@/components/layouts/MetricCard';
import type { DetailPageFetchState } from '@/components/layouts/DetailPageLayout';
import { detailPageQueryErrorSubTitle } from '@/lib/utils/detailPageQueryErrorSubTitle';
import { projetoQualidadeCursorAgentsBase } from '../qualidade-cursor-agents-lista/cursorAgentsPaths';
import type { CursorAgentsDashboardMetrics } from './types';
import { getCursorAgentsCreditUsageColor } from './cursorAgentsDashboardDisplay';

export interface ProjetoQualidadeCursorAgentsDashboardScreenProps {
    projetoId: string;
}

export function ProjetoQualidadeCursorAgentsDashboardScreen({
    projetoId}: ProjetoQualidadeCursorAgentsDashboardScreenProps) {
    const router = useRouter();
    const isMobile = useIsMobile();
    const {
        data: metrics,
        isLoading,
        isError,
        error,
        refetch} = useQueryCache<CursorAgentsDashboardMetrics>({
        queryKey: queryKeys.qa.cursorAgents.dashboard(projetoId),
        endpoint: API_ENDPOINTS.qa.cursorAgents.dashboard,
        params: { projeto_id: projetoId },
        staleTime: 1 * 60 * 1000,
        gcTime: 5 * 60 * 1000});

    const idValid = Boolean(projetoId.trim());

    const fetchState: DetailPageFetchState = useMemo(() => {
        if (!idValid) return 'not_found';
        if (isError) return 'error';
        if (isLoading && !metrics) return 'loading';
        return 'ready';
    }, [idValid, isError, isLoading, metrics]);

    const dashboardQueryErr =
        error instanceof Error ? error : error ? new Error(String(error)) : null;

    const errorSubTitle = useMemo(() => detailPageQueryErrorSubTitle(error), [error]);

    const listaProjetoHref = projetoQualidadeCursorAgentsBase(projetoId);

    const statusChartData = metrics
        ? Object.entries(metrics.agentesPorStatus || {}).map(([status, value]) => ({
              name: status,
              value}))
        : [];

    const topAgentesChartData = metrics
        ? (metrics.topAgentesIa || []).slice(0, 5).map((item) => ({
              name: item.agente_ia_nome,
              value: item.total}))
        : [];

    const creditBlock = metrics?.creditInfo ? (
        <ContentCard
            style={{
                marginBottom: isMobile ? 0 : 24,
                borderLeft: `4px solid ${getCursorAgentsCreditUsageColor(metrics.creditInfo.usage_percentage)}`}}
        >
            <Row justify="space-between" align="middle" style={{ marginBottom: 16 }} gutter={[8, 8]}>
                <Col xs={24} md={16}>
                    <h3 style={{ margin: 0, fontSize: isMobile ? 16 : undefined }}>
                        <CreditCard size={ICON_SIZE_MD} style={{ marginRight: 8 }} aria-hidden />
                        Crédito da API Cursor
                        {metrics.creditInfo.is_estimated ? (
                            <Tag color="warning" style={{ marginLeft: 8 }}>
                                Estimado
                            </Tag>
                        ) : (
                            <Tag color="success" style={{ marginLeft: 8 }}>
                                Real
                            </Tag>
                        )}
                    </h3>
                </Col>
                <Col xs={24} md={8}>
                    <span>
                        Plano: <strong>{metrics.creditInfo.plan.toUpperCase()}</strong>
                    </span>
                </Col>
            </Row>

            <MetricsGrid columns={4} style={{ marginBottom: 16 }}>
                <MetricCard
                    icon={<CircleDollarSign size={ICON_SIZE_MD} aria-hidden />}
                    label="Limite Mensal"
                    value={`$${metrics.creditInfo.credit_limit.toFixed(2)}`}
                    variant="projetos"
                />
                <MetricCard
                    icon={<ArrowDown size={ICON_SIZE_MD} aria-hidden />}
                    label="Usado"
                    value={`$${metrics.creditInfo.credit_used.toFixed(2)}`}
                    variant="projetos"
                />
                <MetricCard
                    icon={<ArrowUp size={ICON_SIZE_MD} aria-hidden />}
                    label="Disponível"
                    value={`$${metrics.creditInfo.credit_available.toFixed(2)}`}
                    variant="concluidos"
                />
                <MetricCard
                    icon={<Percent size={ICON_SIZE_MD} aria-hidden />}
                    label="Percentual Usado"
                    value={`${metrics.creditInfo.usage_percentage.toFixed(1)}%`}
                    variant={
                        metrics.creditInfo.usage_percentage >= 80
                            ? 'projetos'
                            : metrics.creditInfo.usage_percentage >= 60
                              ? 'emAndamento'
                              : 'concluidos'
                    }
                />
            </MetricsGrid>

            <div
                style={{
                    height: 30,
                    backgroundColor: '#f0f0f0',
                    borderRadius: 4,
                    overflow: 'hidden',
                    position: 'relative',
                    marginBottom: 16}}
            >
                <div
                    style={{
                        height: '100%',
                        width: `${Math.min(metrics.creditInfo.usage_percentage, 100)}%`,
                        background: `linear-gradient(90deg, ${getCursorAgentsCreditUsageColor(metrics.creditInfo.usage_percentage)} 0%, ${getCursorAgentsCreditUsageColor(metrics.creditInfo.usage_percentage)}80 100%)`,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        color: 'white',
                        fontWeight: 600}}
                >
                    {metrics.creditInfo.usage_percentage > 5 &&
                        `${metrics.creditInfo.usage_percentage.toFixed(1)}%`}
                </div>
            </div>

            {metrics.creditInfo.usage_percentage >= 80 && (
                <Alert
                    message="Atenção!"
                    description="Você está próximo do limite do seu plano. Considere fazer upgrade ou reduzir o uso de agentes."
                    type="error"
                    showIcon
                />
            )}
            {metrics.creditInfo.usage_percentage >= 60 &&
                metrics.creditInfo.usage_percentage < 80 && (
                    <Alert
                        message="Aviso"
                        description="Você está usando mais de 60% do seu crédito mensal. Monitore o uso para evitar atingir o limite."
                        type="warning"
                        showIcon
                    />
                )}
        </ContentCard>
    ) : null;

    const chartsBlock = (
        <Row gutter={[16, 16]} style={{ marginBottom: isMobile ? 0 : 24 }}>
            <Col xs={24} md={12}>
                <ContentCard title="Agentes por Status">
                    {statusChartData.length > 0 ? (
                        <LazyPieChart data={statusChartData} height={isMobile ? 240 : 300} />
                    ) : (
                        <div style={{ textAlign: 'center', padding: 40, color: '#999' }}>
                            Nenhum dado disponível
                        </div>
                    )}
                </ContentCard>
            </Col>
            <Col xs={24} md={12}>
                <ContentCard title="Top 5 Agentes IA Mais Produtivos">
                    {topAgentesChartData.length > 0 ? (
                        <LazyBarChart
                            data={topAgentesChartData}
                            dataKey="name"
                            bars={[{ key: 'value', name: 'Agentes', color: '#27132e' }]}
                            height={isMobile ? 240 : 300}
                        />
                    ) : (
                        <div style={{ textAlign: 'center', padding: 40, color: '#999' }}>
                            Nenhum dado disponível
                        </div>
                    )}
                </ContentCard>
            </Col>
        </Row>
    );

    const porProjetoBlock =
        metrics?.agentesPorProjeto && metrics.agentesPorProjeto.length > 0 ? (
            <ContentCard title="Agentes por Projeto (Top 10)" style={{ marginBottom: isMobile ? 0 : 24 }}>
                {metrics.agentesPorProjeto.slice(0, 10).map((item, index) => (
                    <div
                        key={index}
                        style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                            padding: '12px',
                            backgroundColor: '#f8f9fa',
                            borderRadius: 8,
                            marginBottom: 8,
                            gap: 12}}
                    >
                        <span style={{ fontWeight: 600, minWidth: 0, wordBreak: 'break-word' }}>
                            {item.projeto_nome}
                        </span>
                        <span style={{ fontSize: 20, fontWeight: 700, flexShrink: 0 }}>{item.total}</span>
                    </div>
                ))}
            </ContentCard>
        ) : null;

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Dashboard Cursor Agents"
            showPageTitleIcon={false}
            titleSection="Dashboard Cursor Agents"
            headerAction={
                fetchState === 'ready' ? (
                    <Link href={listaProjetoHref}>Ver todos</Link>
                ) : undefined
            }
        >
        <DetailPageLayout
            breadcrumbItems={[
                { title: 'Projetos', path: '/projetos' },
                ...(idValid
                    ? [
                          { title: 'Projeto', path: `/projetos/${projetoId}` },
                          {
                              title: 'Agentes Cursor',
                              path: `/projetos/${projetoId}/qualidade/cursor-agents`},
                          { title: 'Dashboard' },
                      ]
                    : [{ title: 'Dashboard' }]),
            ]}
            header={{
                title: 'Dashboard Cursor Agents',
                titleContent: '',
                description: isMobile
                    ? 'Visão agregada dos agentes automatizados.'
                    : 'Métricas e estatísticas dos agentes de desenvolvimento automatizado',
            }}
            fetchState={fetchState}
            error={dashboardQueryErr}
            onRetry={() => void refetch()}
            errorSubTitle={errorSubTitle}
            notFoundTitle="Projeto inválido"
            notFoundSubTitle="O identificador do projeto está ausente ou é inválido na rota."
            notFoundExtra={
                <Button type="primary" onClick={() => router.push('/projetos')}>
                    Voltar para projetos
                </Button>
            }
            wrapChildrenInCard={false}
        >
            {!metrics ? (
                <Empty description="Nenhum dado disponível" />
            ) : (
                <>
            <Alert
                type={metrics.agentesFalhados > 0 ? 'warning' : 'info'}
                showIcon
                style={{ marginBottom: 16 }}
                message="Estado geral da operação de agentes"
                description={
                    <>
                        Falhas registradas: <strong>{metrics.agentesFalhados}</strong> · Ativos:{' '}
                        <strong>{metrics.agentesAtivos}</strong> · Total:{' '}
                        <strong>{metrics.totalAgentes}</strong>.
                        {isMobile
                            ? ' Priorize diagnosticar falhas antes de aumentar a carga.'
                            : ' Priorize diagnosticar falhas recorrentes antes de aumentar carga automatizada.'}
                    </>
                }
            />

            <MetricsGrid columns={4} style={{ marginBottom: 16 }}>
                <MetricCard
                    icon={<Bot size={ICON_SIZE_MD} aria-hidden />}
                    label="Total de Agentes"
                    value={metrics.totalAgentes.toString()}
                    variant="projetos"
                />
                <MetricCard
                    icon={<CheckCircle2 size={ICON_SIZE_MD} aria-hidden />}
                    label="Finalizados com Sucesso"
                    value={metrics.agentesFinalizadosComSucesso.toString()}
                    variant="concluidos"
                />
                <MetricCard
                    icon={<XCircle size={ICON_SIZE_MD} aria-hidden />}
                    label="Falhados"
                    value={metrics.agentesFalhados.toString()}
                    variant="projetos"
                />
                <MetricCard
                    icon={<CirclePlay size={ICON_SIZE_MD} aria-hidden />}
                    label="Agentes Ativos"
                    value={metrics.agentesAtivos.toString()}
                    variant="emAndamento"
                />
            </MetricsGrid>

            <MetricsGrid columns={metrics.tempoMedioExecucao ? 3 : 2} style={{ marginBottom: 16 }}>
                <MetricCard
                    icon={<Percent size={ICON_SIZE_MD} aria-hidden />}
                    label="Taxa de Sucesso"
                    value={`${metrics.taxaSucesso}%`}
                    variant="concluidos"
                />
                <MetricCard
                    icon={<GitBranch size={ICON_SIZE_MD} />}
                    label="PRs Criados"
                    value={metrics.agentesComPR.toString()}
                    variant="projetos"
                />
                {metrics.tempoMedioExecucao && (
                    <MetricCard
                        icon={<Clock size={ICON_SIZE_MD} aria-hidden />}
                        label="Tempo Médio"
                        value={`${metrics.tempoMedioExecucao}min`}
                        variant="projetos"
                    />
                )}
            </MetricsGrid>

            {isMobile ? (
                <Collapse
                    bordered={false}
                    style={{ marginBottom: 16 }}
                    defaultActiveKey={metrics.agentesFalhados > 0 ? ['credito'] : []}
                    items={[
                        ...(creditBlock
                            ? [
                                  {
                                      key: 'credito',
                                      label: 'Crédito da API Cursor',
                                      children: creditBlock,
                                  },
                              ]
                            : []),
                        {
                            key: 'graficos',
                            label: 'Gráficos (status e top agentes)',
                            children: chartsBlock,
                        },
                        ...(porProjetoBlock
                            ? [
                                  {
                                      key: 'projetos',
                                      label: 'Agentes por projeto',
                                      children: porProjetoBlock,
                                  },
                              ]
                            : []),
                    ]}
                />
            ) : (
                <>
                    {creditBlock}
                    {chartsBlock}
                    {porProjetoBlock}
                </>
            )}

            <div style={{ textAlign: 'center', marginTop: 8 }}>
                <Link href={listaProjetoHref}>Ver todos os agentes</Link>
            </div>
                </>
            )}
        </DetailPageLayout>
        </ProjetoLayout>
    );
}
