'use client';

import { BarChart3, CheckCircle2, CirclePause, CirclePlay, Clock, Gauge, GitBranch, ListChecks, PieChart, RefreshCw, TestTube, Trophy } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useState, useMemo, useEffect, useRef } from 'react';
import dynamic from 'next/dynamic';
import { useRouter, useParams } from 'next/navigation';
import {
    Row,
    Col,
    Table,
    Tag,
    Space,
    Select,
    Spin,
    Empty,
    Typography,
    Progress,
    Button,
    Tooltip} from 'antd';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';
import { formatDate } from '@/lib/utils/export';
import dayjs from 'dayjs';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import MetricsGrid from '@/components/layouts/MetricsGrid';
import MetricCard from '@/components/layouts/MetricCard';
import ContentCard from '@/components/layouts/ContentCard';
import { ButtonHeaderIcon } from '@/components/ui';
import { OperativeRouteHint } from '@/components/layouts/OperativeRouteHint/OperativeRouteHint';
import type { ColumnsType } from 'antd/es/table';
import type { Projeto } from '@/types';
import {
    isAplicacaoReactCategoria,
    recordReactModuleSectionOpened,
} from '@/lib/telemetry/aplicacaoReactTelemetry';
import type {
    DistribuicaoStatus,
    EvolucaoTarefas,
    ResumoDesenvolvimento,
    SprintAtiva,
    TopProjeto} from './types';
import { buildDesenvolvimentoDashboardTarefaListaHref } from './buildDesenvolvimentoDashboardTarefaListaHref';

const ClientOnlyRecharts = dynamic(() => import('@/components/charts/ClientOnlyRecharts'), { ssr: false });

const { Text } = Typography;
const { Option } = Select;

const COLORS_STATUS = [
    '#1890ff',
    '#52c41a',
    '#faad14',
    '#ff4d4f',
    '#722ed1',
    '#13c2c2',
    '#eb2f96',
];

export function DesenvolvimentoDashboardScreen() {
    const router = useRouter();
    const params = useParams();
    const routeProjetoId =
        typeof params?.id === 'string' ? params.id : Array.isArray(params?.id) ? params?.id[0] : '';
    const seededProjetoFiltro = useRef(false);
    const [projetoFiltro, setProjetoFiltro] = useState<number | undefined>(undefined);
    const [diasEvolucao, setDiasEvolucao] = useState<number>(30);

    useEffect(() => {
        if (seededProjetoFiltro.current) return;
        const n = Number(routeProjetoId);
        if (routeProjetoId && !Number.isNaN(n)) {
            setProjetoFiltro(n);
            seededProjetoFiltro.current = true;
        }
    }, [routeProjetoId]);

    const { data: projetosResponse } = useQueryCache<{ data: Array<{ id: number; nome: string }> }>(
        {
            queryKey: queryKeys.projetos.listScoped('filters'),
            endpoint: API_ENDPOINTS.projetos.index,
            params: { per_page: 1000 },
            staleTime: 5 * 60 * 1000}
    );

    const projetos = projetosResponse?.data || [];

    const { data: resumo } = useQueryCache<ResumoDesenvolvimento>({
        queryKey: queryKeys.desenvolvimento.dashboard.resumo({ projeto_id: projetoFiltro }),
        endpoint: API_ENDPOINTS.desenvolvimento.dashboard.resumo,
        params: projetoFiltro ? { projeto_id: projetoFiltro } : {},
        staleTime: 1 * 60 * 1000,
        gcTime: 5 * 60 * 1000});

    const { data: distribuicaoStatus, isLoading: loadingStatus } =
        useQueryCache<DistribuicaoStatus>({
            queryKey: queryKeys.desenvolvimento.dashboard.tarefasPorStatus({
                projeto_id: projetoFiltro}),
            endpoint: API_ENDPOINTS.desenvolvimento.dashboard.tarefasPorStatus,
            params: projetoFiltro ? { projeto_id: projetoFiltro } : {},
            staleTime: 1 * 60 * 1000,
            gcTime: 5 * 60 * 1000});

    const { data: distribuicaoPrioridade, isLoading: loadingPrioridade } =
        useQueryCache<DistribuicaoStatus>({
            queryKey: queryKeys.desenvolvimento.dashboard.tarefasPorPrioridade({
                projeto_id: projetoFiltro}),
            endpoint: API_ENDPOINTS.desenvolvimento.dashboard.tarefasPorPrioridade,
            params: projetoFiltro ? { projeto_id: projetoFiltro } : {},
            staleTime: 1 * 60 * 1000,
            gcTime: 5 * 60 * 1000});

    const { data: evolucao, isLoading: loadingEvolucao } = useQueryCache<EvolucaoTarefas>({
        queryKey: queryKeys.desenvolvimento.dashboard.evolucaoTarefas({
            projeto_id: projetoFiltro,
            dias: diasEvolucao}),
        endpoint: `${API_ENDPOINTS.desenvolvimento.dashboard.evolucaoTarefas}?dias=${diasEvolucao}${projetoFiltro ? `&projeto_id=${projetoFiltro}` : ''}`,
        staleTime: 1 * 60 * 1000,
        gcTime: 5 * 60 * 1000});

    const { data: topProjetosResponse, isLoading: loadingTopProjetos } = useQueryCache<{
        projetos: TopProjeto[];
    }>({
        queryKey: queryKeys.desenvolvimento.dashboard.topProjetos(),
        endpoint: API_ENDPOINTS.desenvolvimento.dashboard.topProjetos,
        params: { limite: 10 },
        staleTime: 2 * 60 * 1000,
        gcTime: 10 * 60 * 1000});

    const { data: sprintsAtivasResponse, isLoading: loadingSprintsAtivas } = useQueryCache<{
        sprints: SprintAtiva[];
        total: number;
    }>({
        queryKey: queryKeys.desenvolvimento.dashboard.sprintsAtivas({ projeto_id: projetoFiltro }),
        endpoint: API_ENDPOINTS.desenvolvimento.dashboard.sprintsAtivas,
        params: projetoFiltro ? { projeto_id: projetoFiltro } : {},
        staleTime: 1 * 60 * 1000,
        gcTime: 5 * 60 * 1000});

    const dadosStatus = useMemo(() => {
        if (!distribuicaoStatus?.distribuicao) return [];
        return Object.entries(distribuicaoStatus.distribuicao).map(([status, total]) => ({
            name: status,
            value: total}));
    }, [distribuicaoStatus]);

    const dadosPrioridade = useMemo(() => {
        if (!distribuicaoPrioridade?.distribuicao) return [];
        return Object.entries(distribuicaoPrioridade.distribuicao).map(([prioridade, total]) => ({
            name: prioridade,
            value: total}));
    }, [distribuicaoPrioridade]);

    const dadosEvolucao = useMemo(() => {
        if (!evolucao?.evolucao) return [];
        return evolucao.evolucao.map((item) => ({
            data: item.data_formatada,
            tarefas: item.tarefas_concluidas,
            horas: item.horas_trabalhadas}));
    }, [evolucao]);

    const topProjetosColumns: ColumnsType<TopProjeto> = [
        {
            title: 'Projeto',
            dataIndex: 'projeto_nome',
            key: 'projeto_nome',
            sorter: (a, b) =>
                String(a.projeto_nome ?? '').localeCompare(String(b.projeto_nome ?? ''), 'pt'),
            render: (text: string, record: TopProjeto) => (
                <a
                    href="#"
                    onClick={(e) => {
                        e.preventDefault();
                        router.push(`/projetos/${record.projeto_id}`);
                    }}
                    style={{ fontWeight: 500 }}
                >
                    {text}
                </a>
            )},
        {
            title: 'Total de Tarefas',
            dataIndex: 'total_tarefas',
            key: 'total_tarefas',
            align: 'right',
            sorter: (a, b) => (a.total_tarefas ?? 0) - (b.total_tarefas ?? 0),
            render: (total: number) => <Tag color="blue">{total}</Tag>},
    ];

    const sprintsAtivasColumns: ColumnsType<SprintAtiva> = [
        {
            title: 'Sprint',
            dataIndex: 'nome',
            key: 'nome',
            sorter: (a, b) => String(a.nome ?? '').localeCompare(String(b.nome ?? ''), 'pt'),
            render: (text: string, record: SprintAtiva) => (
                <a
                    href="#"
                    onClick={(e) => {
                        e.preventDefault();
                        router.push(`/desenvolvimento/sprints/${record.id}`);
                    }}
                    style={{ fontWeight: 500 }}
                >
                    {text}
                </a>
            )},
        {
            title: 'Projeto',
            dataIndex: ['projeto', 'nome'],
            key: 'projeto',
            sorter: (a, b) =>
                String(a.projeto?.nome ?? '').localeCompare(String(b.projeto?.nome ?? ''), 'pt'),
            render: (text: string, record: SprintAtiva) =>
                record.projeto ? (
                    <a
                        href="#"
                        onClick={(e) => {
                            e.preventDefault();
                            router.push(`/projetos/${record.projeto?.id}`);
                        }}
                    >
                        {text}
                    </a>
                ) : (
                    '-'
                )},
        {
            title: 'Período',
            key: 'periodo',
            sorter: (a, b) => dayjs(a.data_inicio).valueOf() - dayjs(b.data_inicio).valueOf(),
            render: (_: unknown, record: SprintAtiva) => (
                <Text type="secondary">
                    {formatDate(record.data_inicio)} - {formatDate(record.data_fim)}
                </Text>
            )},
        {
            title: 'Progresso',
            key: 'progresso',
            sorter: (a, b) => (a.progresso ?? 0) - (b.progresso ?? 0),
            render: (_: unknown, record: SprintAtiva) => (
                <div>
                    <Progress
                        percent={record.progresso}
                        status={record.progresso === 100 ? 'success' : 'active'}
                    />
                    <Text type="secondary" style={{ fontSize: 12 }}>
                        {record.tarefas_concluidas} / {record.tarefas_total}
                    </Text>
                </div>
            )},
    ];

    return (
        <ProjetoLayout
            projetoId={routeProjetoId}
            pageTitle="Dashboard desenvolvimento"
            showPageTitleIcon={false}
            titleSection="Dashboard desenvolvimento"
            headerAction={
                    <Space wrap size={8} align="center">
                        <Tooltip title="Filtrar gráficos e tabelas por projeto">
                            <span style={{ display: 'inline-block' }}>
                                <Select
                                    placeholder="Filtrar por projeto"
                                    allowClear
                                    style={{ width: 200 }}
                                    value={projetoFiltro}
                                    onChange={setProjetoFiltro}
                                >
                                    {projetos.map((projeto) => (
                                        <Option key={projeto.id} value={projeto.id}>
                                            {projeto.nome}
                                        </Option>
                                    ))}
                                </Select>
                            </span>
                        </Tooltip>
                        <Tooltip title="Recarregar a página e os dados do dashboard">
                            <span style={{ display: 'inline-block' }}>
                                <ButtonHeaderIcon
                                    icon={<RefreshCw size={ICON_SIZE_MD} aria-hidden />}
                                    title="Atualizar"
                                    onClick={() => window.location.reload()}
                                />
                            </span>
                        </Tooltip>
                    </Space>
            }
        >
            {routeProjetoId ? (
                <OperativeRouteHint
                    message="Próximas ações"
                    description="Quando identificar concentração de risco (atrasos, fila parada), abra o board ou a fila de execução assistida no mesmo projeto."
                >
                    <Space wrap>
                        <Button type="primary" onClick={() => router.push(`/projetos/${routeProjetoId}/kanban`)}>
                            Abrir Kanban
                        </Button>
                        <Button onClick={() => router.push(`/projetos/${routeProjetoId}/desenvolvimento/fila-cursor`)}>
                            Fila Cursor (ERP)
                        </Button>
                        <Button onClick={() => router.push(`/projetos/${routeProjetoId}/planejamento/backlog`)}>
                            Backlog técnico
                        </Button>
                    </Space>
                </OperativeRouteHint>
            ) : (
                <OperativeRouteHint
                    message="Recorte sugerido"
                    description="Selecione um projeto no filtro acima para contextualizar gráficos e comparar com o trabalho em andamento."
                />
            )}

            <MetricsGrid columns={4} style={{ marginBottom: 24 }}>
                <MetricCard
                    label="Total de Tarefas"
                    value={resumo?.tarefas.total || 0}
                    subvalue={`${resumo?.tarefas.concluidas || 0} concluídas — clique para listar`}
                    icon={<ListChecks size={ICON_SIZE_MD} aria-hidden />}
                    variant="projetos"
                    onClick={() =>
                        router.push(
                            buildDesenvolvimentoDashboardTarefaListaHref({
                                projetoId: projetoFiltro ?? routeProjetoId,
                            }),
                        )
                    }
                />
                <MetricCard
                    label="Taxa de Conclusão"
                    value={`${resumo?.tarefas.taxa_conclusao || 0}%`}
                    subvalue="Tarefas concluídas"
                    icon={<CheckCircle2 size={ICON_SIZE_MD} aria-hidden />}
                    variant={
                        resumo?.tarefas.taxa_conclusao && resumo.tarefas.taxa_conclusao >= 80
                            ? 'concluidos'
                            : 'emAndamento'
                    }
                />
                <MetricCard
                    label="Horas Trabalhadas"
                    value={`${resumo?.horas.total_trabalhadas || 0}h`}
                    subvalue={`de ${resumo?.horas.total_estimadas || 0}h estimadas`}
                    icon={<Clock size={ICON_SIZE_MD} aria-hidden />}
                    variant="projetos"
                />
                <MetricCard
                    label="Sprints Ativas"
                    value={resumo?.sprints.ativas || 0}
                    subvalue={`${resumo?.sprints.total || 0} total`}
                    icon={<Gauge size={ICON_SIZE_MD} />}
                    variant="emAndamento"
                    onClick={() => {
                        const pid = projetoFiltro ?? (routeProjetoId ? Number(routeProjetoId) : undefined);
                        if (pid && Number.isFinite(pid)) {
                            router.push(`/projetos/${pid}/planejamento/sprints`);
                        }
                    }}
                />
            </MetricsGrid>

            <MetricsGrid columns={6} style={{ marginBottom: 24 }}>
                <MetricCard
                    label="Em Andamento"
                    value={resumo?.tarefas.em_andamento || 0}
                    subvalue="Clique para listar"
                    icon={<CirclePlay size={ICON_SIZE_MD} aria-hidden />}
                    variant="emAndamento"
                    onClick={() =>
                        router.push(
                            buildDesenvolvimentoDashboardTarefaListaHref({
                                status: 'em_andamento',
                                projetoId: projetoFiltro ?? routeProjetoId,
                            }),
                        )
                    }
                />
                <MetricCard
                    label="Em revisão"
                    value={resumo?.tarefas.em_code_review || 0}
                    subvalue="Status code_review — clique para listar"
                    icon={<GitBranch size={ICON_SIZE_MD} aria-hidden />}
                    variant="emAndamento"
                    onClick={() =>
                        router.push(
                            buildDesenvolvimentoDashboardTarefaListaHref({
                                status: 'code_review',
                                projetoId: projetoFiltro ?? routeProjetoId,
                            }),
                        )
                    }
                />
                <MetricCard
                    label="Em Teste"
                    value={resumo?.tarefas.em_teste || 0}
                    subvalue="Clique para listar"
                    icon={<TestTube size={ICON_SIZE_MD} aria-hidden />}
                    variant="emAndamento"
                    onClick={() =>
                        router.push(
                            buildDesenvolvimentoDashboardTarefaListaHref({
                                status: 'teste',
                                projetoId: projetoFiltro ?? routeProjetoId,
                            }),
                        )
                    }
                />
                <MetricCard
                    label="Pendentes"
                    value={resumo?.tarefas.pendentes || 0}
                    subvalue="Filtro lista: Pendente (novo)"
                    icon={<CirclePause size={ICON_SIZE_MD} aria-hidden />}
                    variant="projetos"
                    onClick={() =>
                        router.push(
                            buildDesenvolvimentoDashboardTarefaListaHref({
                                status: 'novo',
                                projetoId: projetoFiltro ?? routeProjetoId,
                            }),
                        )
                    }
                />
                <MetricCard
                    label="Projetos Ativos"
                    value={resumo?.projetos.ativos || 0}
                    subvalue={`${resumo?.projetos.total || 0} total`}
                    icon={<GitBranch size={ICON_SIZE_MD} aria-hidden />}
                    variant="emAndamento"
                />
                <MetricCard
                    label="Progresso Médio"
                    value={`${resumo?.horas.progresso_medio || 0}%`}
                    subvalue="Horas trabalhadas"
                    icon={<PieChart size={ICON_SIZE_MD} aria-hidden />}
                    variant={
                        resumo?.horas.progresso_medio && resumo.horas.progresso_medio >= 80
                            ? 'concluidos'
                            : 'emAndamento'
                    }
                />
            </MetricsGrid>

            <Row gutter={16} style={{ marginBottom: 24 }}>
                <Col xs={24} lg={16}>
                    <ContentCard
                        title="Evolução de Tarefas Concluídas"
                        icon={<BarChart3 size={ICON_SIZE_MD} aria-hidden />}
                        headerActions={
                            <Select
                                value={diasEvolucao}
                                onChange={setDiasEvolucao}
                                style={{ width: 120 }}
                            >
                                <Option value={7}>7 dias</Option>
                                <Option value={30}>30 dias</Option>
                                <Option value={90}>90 dias</Option>
                            </Select>
                        }
                    >
                        {loadingEvolucao ? (
                            <div style={{ textAlign: 'center', padding: '50px' }}>
                                <Spin />
                            </div>
                        ) : dadosEvolucao.length === 0 ? (
                            <Empty description="Nenhum dado disponível" />
                        ) : (
                            <ClientOnlyRecharts>
                                {(recharts) => {
                                    const {
                                        ResponsiveContainer,
                                        LineChart,
                                        Line,
                                        XAxis,
                                        YAxis,
                                        CartesianGrid,
                                        Tooltip,
                                        Legend} = recharts;
                                    return (
                                        <ResponsiveContainer width="100%" height={300}>
                                            <LineChart data={dadosEvolucao}>
                                                <CartesianGrid strokeDasharray="3 3" />
                                                <XAxis dataKey="data" />
                                                <YAxis />
                                                <Tooltip />
                                                <Legend />
                                                <Line
                                                    type="monotone"
                                                    dataKey="tarefas"
                                                    stroke="#1890ff"
                                                    name="Tarefas Concluídas"
                                                />
                                                <Line
                                                    type="monotone"
                                                    dataKey="horas"
                                                    stroke="#52c41a"
                                                    name="Horas Trabalhadas"
                                                />
                                            </LineChart>
                                        </ResponsiveContainer>
                                    );
                                }}
                            </ClientOnlyRecharts>
                        )}
                    </ContentCard>
                </Col>

                <Col xs={24} lg={8}>
                    <ContentCard
                        title="Tarefas por Status"
                        icon={<PieChart size={ICON_SIZE_MD} aria-hidden />}
                    >
                        {loadingStatus ? (
                            <div style={{ textAlign: 'center', padding: '50px' }}>
                                <Spin />
                            </div>
                        ) : dadosStatus.length === 0 ? (
                            <Empty description="Nenhum dado disponível" />
                        ) : (
                            <ClientOnlyRecharts>
                                {(recharts) => {
                                    const { ResponsiveContainer, PieChart, Pie, Cell, Tooltip } =
                                        recharts;
                                    return (
                                        <ResponsiveContainer width="100%" height={300}>
                                            <PieChart>
                                                <Pie
                                                    data={dadosStatus}
                                                    cx="50%"
                                                    cy="50%"
                                                    labelLine={false}
                                                    label={({
                                                        name,
                                                        percent}: {
                                                        name: string;
                                                        percent: number;
                                                    }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                                                    outerRadius={80}
                                                    fill="#8884d8"
                                                    dataKey="value"
                                                >
                                                    {dadosStatus.map((entry, index) => (
                                                        <Cell
                                                            key={`cell-${index}`}
                                                            fill={
                                                                COLORS_STATUS[
                                                                    index % COLORS_STATUS.length
                                                                ]
                                                            }
                                                        />
                                                    ))}
                                                </Pie>
                                                <Tooltip />
                                            </PieChart>
                                        </ResponsiveContainer>
                                    );
                                }}
                            </ClientOnlyRecharts>
                        )}
                    </ContentCard>
                </Col>
            </Row>

            <Row gutter={16} style={{ marginBottom: 24 }}>
                <Col xs={24} lg={12}>
                    <ContentCard
                        title="Tarefas por Prioridade"
                        icon={<BarChart3 size={ICON_SIZE_MD} aria-hidden />}
                    >
                        {loadingPrioridade ? (
                            <div style={{ textAlign: 'center', padding: '50px' }}>
                                <Spin />
                            </div>
                        ) : dadosPrioridade.length === 0 ? (
                            <Empty description="Nenhum dado disponível" />
                        ) : (
                            <ClientOnlyRecharts>
                                {(recharts) => {
                                    const {
                                        ResponsiveContainer,
                                        BarChart,
                                        Bar,
                                        XAxis,
                                        YAxis,
                                        CartesianGrid,
                                        Tooltip} = recharts;
                                    return (
                                        <ResponsiveContainer width="100%" height={300}>
                                            <BarChart data={dadosPrioridade}>
                                                <CartesianGrid strokeDasharray="3 3" />
                                                <XAxis dataKey="name" />
                                                <YAxis />
                                                <Tooltip />
                                                <Bar dataKey="value" fill="#1890ff" />
                                            </BarChart>
                                        </ResponsiveContainer>
                                    );
                                }}
                            </ClientOnlyRecharts>
                        )}
                    </ContentCard>
                </Col>

                <Col xs={24} lg={12}>
                    <ContentCard
                        title="Top 10 Projetos por Tarefas"
                        icon={<Trophy size={ICON_SIZE_MD} aria-hidden />}
                    >
                        {loadingTopProjetos ? (
                            <div style={{ textAlign: 'center', padding: '50px' }}>
                                <Spin />
                            </div>
                        ) : !topProjetosResponse?.projetos ||
                          topProjetosResponse.projetos.length === 0 ? (
                            <Empty description="Nenhum projeto encontrado" />
                        ) : (
                            <Table
                                columns={topProjetosColumns}
                                dataSource={topProjetosResponse.projetos}
                                rowKey="projeto_id"
                                pagination={false}
                            />
                        )}
                    </ContentCard>
                </Col>
            </Row>

            <ContentCard
                title={`Sprints Ativas (${sprintsAtivasResponse?.total || 0})`}
                icon={<Gauge size={ICON_SIZE_MD} />}
            >
                {loadingSprintsAtivas ? (
                    <div style={{ textAlign: 'center', padding: '50px' }}>
                        <Spin />
                    </div>
                ) : !sprintsAtivasResponse?.sprints ||
                  sprintsAtivasResponse.sprints.length === 0 ? (
                    <Empty description="Nenhuma sprint ativa no momento" />
                ) : (
                    <Table
                        columns={sprintsAtivasColumns}
                        dataSource={sprintsAtivasResponse.sprints}
                        rowKey="id"
                        pagination={false}
                    />
                )}
            </ContentCard>
        </ProjetoLayout>
    );
}
