'use client';

import { confirmDialog } from '@/lib/feedback/confirmDialog';

/**
 * Planejamento de um projeto — extraído de app/(dashboard)/projetos/[id]/planejamento (FRONT-S2-02.x / inventário #1).
 *
 * @route /projetos/[id]/planejamento
 */

import { AlignLeft, BarChart3, Box, Calendar, Check, CheckCircle2, ChevronLeft, CirclePlay, Clock, Eye, FileText, History, List, Loader2, PieChart, SquareCheck, StickyNote, TriangleAlert } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useState } from 'react';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/navigation';
import { Alert, Button, Col, Descriptions, Empty, Modal, Row, Space, Spin, Table, Tabs, Tag, Timeline, Tooltip, Typography } from 'antd';
import { message } from '@/lib/feedback/message';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useMutationCache } from '@/hooks/useMutationCache';
import { useResponsiveModalProps } from '@/hooks/useResponsiveModalProps';
import { queryKeys } from '@/lib/cache/queryKeys';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { formatDate } from '@/lib/utils/export';
import dayjs from 'dayjs';
import type { ColumnsType } from 'antd/es/table';
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 type { PlanoProjeto, PlanejamentoResumo, ProjetoPlanejamentoApiData } from './types';

const LazyBarChart = dynamic(
    () => import('@/components/lazy').then((m) => m.LazyBarChart),
    { ssr: false },
);

const { Paragraph, Text } = Typography;

export interface ProjetoPlanejamentoScreenProps {
    projetoId: string;
}

export function ProjetoPlanejamentoScreen({ projetoId }: ProjetoPlanejamentoScreenProps) {
    const router = useRouter();
    const [activeTab, setActiveTab] = useState('fases');
    const [modalVersaoVisible, setModalVersaoVisible] = useState(false);
    const [versaoSelecionada, setVersaoSelecionada] = useState<PlanoProjeto | null>(null);
    const versaoModalLayout = useResponsiveModalProps();

    const {
        data: planejamentoData,
        isLoading,
        error,
        refetch: refetchPlanejamento} = useQueryCache<ProjetoPlanejamentoApiData>({
        queryKey: queryKeys.projetos.planejamento(projetoId),
        endpoint: API_ENDPOINTS.projetos.planejamento(projetoId),
        staleTime: 2 * 60 * 1000,
        gcTime: 10 * 60 * 1000,
        enabled: !!projetoId});

    const {
        data: versoesData,
        isLoading: loadingVersoes,
        refetch: refetchVersoes} = useQueryCache<PlanoProjeto[]>({
        queryKey: queryKeys.planosProjeto.byProjeto(projetoId),
        endpoint: API_ENDPOINTS.planejamento.index,
        params: { projeto_id: projetoId },
        staleTime: 2 * 60 * 1000,
        gcTime: 10 * 60 * 1000,
        enabled: !!projetoId});

    const { data: versaoAprovadaData, refetch: refetchVersaoAprovada } =
        useQueryCache<PlanoProjeto>({
            queryKey: queryKeys.planosProjeto.aprovada(projetoId),
            endpoint: API_ENDPOINTS.planejamento.versaoAprovada,
            params: { projeto_id: projetoId },
            staleTime: 2 * 60 * 1000,
            gcTime: 10 * 60 * 1000,
            enabled: !!projetoId});

    const aprovarVersaoMutation = useMutationCache<unknown, { planoId: number }>({
        endpoint: (variables) => API_ENDPOINTS.planejamento.aprovar(variables.planoId),
        method: 'POST',
        invalidateQueries: [
            queryKeys.planosProjeto.byProjeto(projetoId),
            queryKeys.projetos.planejamento(projetoId),
        ],
        onSuccess: () => {
            message.success('Versão aprovada com sucesso!');
            refetchVersoes();
            refetchVersaoAprovada();
            refetchPlanejamento();
        },
        onError: (err: unknown) => {
            const errorMessage =
                (err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
                'Erro ao aprovar versão';
            message.error(errorMessage);
        }});

    const fases = planejamentoData?.fases || [];
    const resumo: Partial<PlanejamentoResumo> = planejamentoData?.resumo || {};
    const versoes = versoesData || [];
    const versaoAprovada = versaoAprovadaData;

    const getStatusColor = (status: string) => {
        const colors: Record<string, string> = {
            planejado: 'default',
            em_andamento: 'processing',
            concluido: 'success',
            atrasado: 'error'};
        return colors[status] || 'default';
    };

    const getStatusIcon = (status: string) => {
        const icons: Record<string, React.ReactNode> = {
            planejado: <Clock size={ICON_SIZE_MD} aria-hidden />,
            em_andamento: <Loader2 size={ICON_SIZE_MD} className="animate-spin" aria-hidden />,
            concluido: <CheckCircle2 size={ICON_SIZE_MD} aria-hidden />,
            atrasado: <TriangleAlert size={ICON_SIZE_MD} aria-hidden />};
        return icons[status] || null;
    };

    const getStatusPlanoColor = (status: string) => {
        const colors: Record<string, string> = {
            rascunho: 'default',
            em_revisao: 'processing',
            aprovado: 'success',
            rejeitado: 'error'};
        return colors[status] || 'default';
    };

    const handleAprovarVersao = (plano: PlanoProjeto) => {
        confirmDialog({
            title: 'Confirmar aprovação',
            content: `Tem certeza que deseja aprovar a versão "${plano.versao}" do plano "${plano.nome}"?`,
            okText: 'Aprovar',
            okType: 'primary',
            cancelText: 'Cancelar',
            onOk: () => {
                aprovarVersaoMutation.mutate({ planoId: plano.id });
            }});
    };

    const handleVisualizarVersao = (plano: PlanoProjeto) => {
        setVersaoSelecionada(plano);
        setModalVersaoVisible(true);
    };

    const columnsVersoes: ColumnsType<PlanoProjeto> = [
        {
            title: 'Versão',
            dataIndex: 'versao',
            key: 'versao',
            sorter: (a, b) =>
                String(a.versao ?? '').localeCompare(String(b.versao ?? ''), 'pt', { numeric: true }),
            render: (versao: string, record: PlanoProjeto) => (
                <Space>
                    <Text strong>v{versao}</Text>
                    {versaoAprovada?.id === record.id && (
                        <Tag color="green" icon={<Check size={ICON_SIZE_MD} aria-hidden />}>
                            Aprovada
                        </Tag>
                    )}
                </Space>
            )},
        {
            title: 'Nome',
            dataIndex: 'nome',
            key: 'nome',
            sorter: (a, b) => String(a.nome ?? '').localeCompare(String(b.nome ?? ''), 'pt'),
            render: (nome: string) => <Text strong>{nome}</Text>},
        {
            title: 'Status',
            dataIndex: 'status',
            key: 'status',
            sorter: (a, b) => String(a.status ?? '').localeCompare(String(b.status ?? ''), 'pt'),
            render: (status: string) => (
                <Tag color={getStatusPlanoColor(status)}>
                    {status.replace('_', ' ').toUpperCase()}
                </Tag>
            )},
        {
            title: 'Criado em',
            dataIndex: 'created_at',
            key: 'created_at',
            sorter: (a, b) => dayjs(a.created_at).valueOf() - dayjs(b.created_at).valueOf(),
            render: (date: string) => formatDate(date, true)},
        {
            title: 'Aprovado em',
            dataIndex: 'aprovado_em',
            key: 'aprovado_em',
            sorter: (a, b) =>
                dayjs(a.aprovado_em).valueOf() - dayjs(b.aprovado_em).valueOf(),
            render: (date?: string) => (date ? formatDate(date) : '-')},
        {
            title: 'Ações',
            key: 'actions',
            width: 200,
            render: (_: unknown, record: PlanoProjeto) => (
                <Space>
                    <Button
                        type="link"
                        icon={<Eye size={ICON_SIZE_MD} aria-hidden />}
                        onClick={() => handleVisualizarVersao(record)}
                    >
                        Visualizar
                    </Button>
                    {record.status !== 'aprovado' && (
                        <Button
                            type="link"
                            icon={<Check size={ICON_SIZE_MD} aria-hidden />}
                            style={{ color: '#52c41a' }}
                            onClick={() => handleAprovarVersao(record)}
                        >
                            Aprovar
                        </Button>
                    )}
                </Space>
            )},
    ];

    if (isLoading) {
        return (
            <ProjetoLayout
                projetoId={projetoId}
                pageTitle="Planejamento"
                showPageTitleIcon={false}
                titleSection="Planejamento"
            >
                <div style={{ textAlign: 'center', padding: '50px' }}>
                    <Spin size="large" />
                </div>
            </ProjetoLayout>
        );
    }

    if (error) {
        return (
            <ProjetoLayout
                projetoId={projetoId}
                pageTitle="Planejamento"
                showPageTitleIcon={false}
                titleSection="Planejamento"
            >
                <Alert
                    message="Erro ao carregar planejamento"
                    description={error instanceof Error ? error.message : 'Erro desconhecido'}
                    type="error"
                    showIcon
                    action={
                        <Button size="small" onClick={() => router.push(`/projetos/${projetoId}`)}>
                            Voltar
                        </Button>
                    }
                />
            </ProjetoLayout>
        );
    }

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Planejamento"
            showPageTitleIcon={false}
            titleSection="Planejamento"
            headerAction={
                    <Space wrap size={8} align="center">
                        <Tooltip title="Voltar ao projeto">
                            <span style={{ display: 'inline-block' }}>
                                <ButtonHeaderIcon
                                    icon={<ChevronLeft size={ICON_SIZE_MD} aria-hidden />}
                                    title="Voltar"
                                    onClick={() => router.push(`/projetos/${projetoId}`)}
                                />
                            </span>
                        </Tooltip>
                    </Space>
            }
        >
            <Alert
                type="info"
                showIcon
                style={{ marginBottom: 24 }}
                message="Prioridades, dependências e próximos passos"
                description={
                    <Space direction="vertical" size="small" style={{ width: '100%' }}>
                        <span>
                            Use as fases para sequenciar o trabalho; valide a versão aprovada do plano antes de
                            comprometer entregas externas. Desbloqueie dependências entre fases antes de aumentar
                            paralelismo.
                        </span>
                        <Space wrap>
                            <Button type="link" size="small" onClick={() => router.push(`/projetos/${projetoId}/planejamento/backlog`)}>
                                Backlog de planejamento
                            </Button>
                            <Button type="link" size="small" onClick={() => router.push(`/projetos/${projetoId}/planejamento/gantt`)}>
                                Gantt / cronograma
                            </Button>
                            <Button type="link" size="small" onClick={() => router.push(`/projetos/${projetoId}/planejamento/entregas`)}>
                                Entregas
                            </Button>
                            <Button type="link" size="small" onClick={() => router.push(`/projetos/${projetoId}/orcamento`)}>
                                Orçamento
                            </Button>
                        </Space>
                    </Space>
                }
            />

            {resumo && (
                <MetricsGrid columns={4} style={{ marginBottom: 24 }}>
                    <MetricCard
                        icon={<List size={ICON_SIZE_MD} aria-hidden />}
                        label="Total de Fases"
                        value={resumo.total_fases || 0}
                        variant="projetos"
                    />
                    <MetricCard
                        icon={<CheckCircle2 size={ICON_SIZE_MD} aria-hidden />}
                        label="Concluídas"
                        value={resumo.fases_concluidas || 0}
                        variant="concluidos"
                    />
                    <MetricCard
                        icon={<CirclePlay size={ICON_SIZE_MD} aria-hidden />}
                        label="Em Andamento"
                        value={resumo.fases_em_andamento || 0}
                        variant="emAndamento"
                    />
                    <MetricCard
                        icon={<TriangleAlert size={ICON_SIZE_MD} aria-hidden />}
                        label="Atrasadas"
                        value={resumo.fases_atrasadas || 0}
                        variant="gradientRed"
                    />
                </MetricsGrid>
            )}

            <ContentCard>
                <Tabs
                    activeKey={activeTab}
                    onChange={setActiveTab}
                    items={[
                        {
                            key: 'fases',
                            label: (
                                <span>
                                    <Calendar size={ICON_SIZE_MD} style={{ marginRight: 8 }} aria-hidden />
                                    Fases do Planejamento
                                </span>
                            ),
                            children: (
                                <ContentCard
                                    title="Fases do Planejamento"
                                    icon={<List size={ICON_SIZE_MD} aria-hidden />}
                                >
                                    <Timeline
                                        items={fases.map((fase) => ({
                                            color:
                                                getStatusColor(fase.status) === 'success'
                                                    ? 'green'
                                                    : getStatusColor(fase.status) === 'error'
                                                      ? 'red'
                                                      : 'blue',
                                            children: (
                                                <div>
                                                    <div
                                                        style={{
                                                            display: 'flex',
                                                            justifyContent: 'space-between',
                                                            alignItems: 'center',
                                                            marginBottom: 8}}
                                                    >
                                                        <div>
                                                            <strong style={{ fontSize: 16 }}>
                                                                {fase.fase}
                                                            </strong>
                                                            <Tag
                                                                color={getStatusColor(fase.status)}
                                                                icon={getStatusIcon(fase.status)}
                                                                style={{ marginLeft: 8 }}
                                                            >
                                                                {fase.status
                                                                    .replace('_', ' ')
                                                                    .toUpperCase()}
                                                            </Tag>
                                                        </div>
                                                    </div>
                                                    {fase.descricao && (
                                                        <Paragraph
                                                            style={{
                                                                marginBottom: 8,
                                                                color: '#666'}}
                                                        >
                                                            {fase.descricao}
                                                        </Paragraph>
                                                    )}
                                                    <Space>
                                                        {fase.data_inicio && (
                                                            <span>
                                                                <Calendar size={ICON_SIZE_MD} style={{ marginRight: 4 }} aria-hidden />
                                                                Início:{' '}
                                                                {formatDate(fase.data_inicio)}
                                                            </span>
                                                        )}
                                                        {fase.data_fim && (
                                                            <span>
                                                                <Calendar size={ICON_SIZE_MD} style={{ marginRight: 4 }} aria-hidden />
                                                                Fim: {formatDate(fase.data_fim)}
                                                            </span>
                                                        )}
                                                        {fase.responsavel && (
                                                            <span>
                                                                Responsável: {fase.responsavel.nome}
                                                            </span>
                                                        )}
                                                    </Space>
                                                </div>
                                            )}))}
                                    />
                                </ContentCard>
                            )},
                        {
                            key: 'versoes',
                            label: (
                                <span>
                                    <History size={ICON_SIZE_MD} style={{ marginRight: 8 }} aria-hidden />
                                    Versões ({versoes.length})
                                </span>
                            ),
                            children: (
                                <div>
                                    {versaoAprovada && (
                                        <Alert
                                            message={`Versão Aprovada: v${versaoAprovada.versao} - ${versaoAprovada.nome}`}
                                            description={`Aprovada em ${versaoAprovada.aprovado_em ? formatDate(versaoAprovada.aprovado_em) : 'N/A'}`}
                                            type="success"
                                            showIcon
                                            style={{ marginBottom: 24 }}
                                        />
                                    )}
                                    <ContentCard
                                        title="Histórico de Versões"
                                        icon={<History size={ICON_SIZE_MD} aria-hidden />}
                                    >
                                        {loadingVersoes ? (
                                            <div style={{ textAlign: 'center', padding: 40 }}>
                                                <Spin />
                                            </div>
                                        ) : versoes.length > 0 ? (
                                            <Table
                                                columns={columnsVersoes}
                                                dataSource={versoes}
                                                rowKey="id"
                                                pagination={{ pageSize: 10, showSizeChanger: true }}
                                            />
                                        ) : (
                                            <Empty description="Nenhuma versão de plano encontrada" />
                                        )}
                                    </ContentCard>
                                </div>
                            )},
                        {
                            key: 'visualizacoes',
                            label: (
                                <span>
                                    <BarChart3 size={ICON_SIZE_MD} style={{ marginRight: 8 }} aria-hidden />
                                    Visualizações
                                </span>
                            ),
                            children: (
                                <Row gutter={[16, 16]}>
                                    <Col xs={24} lg={12}>
                                        <ContentCard
                                            title="Status das Fases"
                                            icon={<BarChart3 size={ICON_SIZE_MD} aria-hidden />}
                                        >
                                            {fases.length > 0 ? (
                                                <LazyBarChart
                                                    data={[
                                                        {
                                                            status: 'Concluídas',
                                                            quantidade:
                                                                resumo.fases_concluidas || 0},
                                                        {
                                                            status: 'Em Andamento',
                                                            quantidade:
                                                                resumo.fases_em_andamento || 0},
                                                        {
                                                            status: 'Atrasadas',
                                                            quantidade:
                                                                resumo.fases_atrasadas || 0},
                                                        {
                                                            status: 'Planejadas',
                                                            quantidade:
                                                                (resumo.total_fases || 0) -
                                                                (resumo.fases_concluidas || 0) -
                                                                (resumo.fases_em_andamento || 0) -
                                                                (resumo.fases_atrasadas || 0)},
                                                    ]}
                                                    dataKey="status"
                                                    bars={[
                                                        {
                                                            key: 'quantidade',
                                                            name: 'Quantidade',
                                                            color: '#27132e'},
                                                    ]}
                                                    height={300}
                                                />
                                            ) : (
                                                <Empty description="Sem dados para exibir" />
                                            )}
                                        </ContentCard>
                                    </Col>
                                    <Col xs={24} lg={12}>
                                        <ContentCard
                                            title="Distribuição de Versões"
                                            icon={<PieChart size={ICON_SIZE_MD} aria-hidden />}
                                        >
                                            {versoes.length > 0 ? (
                                                <LazyBarChart
                                                    data={[
                                                        {
                                                            status: 'Aprovadas',
                                                            quantidade: versoes.filter(
                                                                (v) => v.status === 'aprovado'
                                                            ).length},
                                                        {
                                                            status: 'Em Revisão',
                                                            quantidade: versoes.filter(
                                                                (v) => v.status === 'em_revisao'
                                                            ).length},
                                                        {
                                                            status: 'Rascunho',
                                                            quantidade: versoes.filter(
                                                                (v) => v.status === 'rascunho'
                                                            ).length},
                                                        {
                                                            status: 'Rejeitadas',
                                                            quantidade: versoes.filter(
                                                                (v) => v.status === 'rejeitado'
                                                            ).length},
                                                    ]}
                                                    dataKey="status"
                                                    bars={[
                                                        {
                                                            key: 'quantidade',
                                                            name: 'Quantidade',
                                                            color: '#27ae60'},
                                                    ]}
                                                    height={300}
                                                />
                                            ) : (
                                                <Empty description="Sem versões para exibir" />
                                            )}
                                        </ContentCard>
                                    </Col>
                                </Row>
                            )},
                    ]}
                />
            </ContentCard>

            <Modal
                title={
                    <Space>
                        <FileText size={ICON_SIZE_MD} aria-hidden />
                        Versão {versaoSelecionada?.versao} - {versaoSelecionada?.nome}
                    </Space>
                }
                open={modalVersaoVisible}
                onCancel={() => {
                    setModalVersaoVisible(false);
                    setVersaoSelecionada(null);
                }}
                footer={[
                    <Button
                        key="close"
                        onClick={() => {
                            setModalVersaoVisible(false);
                            setVersaoSelecionada(null);
                        }}
                    >
                        Fechar
                    </Button>,
                ]}
                width={versaoModalLayout.width ?? 900}
                centered={versaoModalLayout.centered}
                styles={versaoModalLayout.styles}
                destroyOnHidden
                keyboard
                focusTriggerAfterClose
                data-testid="projeto-planejamento-versao-detalhes-modal"
            >
                {versaoSelecionada && (
                    <div>
                        <Descriptions bordered column={2} style={{ marginBottom: 24 }}>
                            <Descriptions.Item label="Versão">
                                v{versaoSelecionada.versao}
                            </Descriptions.Item>
                            <Descriptions.Item label="Status">
                                <Tag color={getStatusPlanoColor(versaoSelecionada.status)}>
                                    {versaoSelecionada.status.replace('_', ' ').toUpperCase()}
                                </Tag>
                            </Descriptions.Item>
                            <Descriptions.Item label="Criado em" span={2}>
                                {formatDate(versaoSelecionada.created_at)}
                            </Descriptions.Item>
                            {versaoSelecionada.aprovado_em && (
                                <>
                                    <Descriptions.Item label="Aprovado em">
                                        {formatDate(versaoSelecionada.aprovado_em)}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="Aprovado por">
                                        {versaoSelecionada.aprovado_por || '-'}
                                    </Descriptions.Item>
                                </>
                            )}
                        </Descriptions>

                        {versaoSelecionada.descricao && (
                            <ContentCard
                                title="Descrição"
                                icon={<AlignLeft size={ICON_SIZE_MD} aria-hidden />}
                                style={{ marginBottom: 16 }}
                            >
                                <Paragraph>{versaoSelecionada.descricao}</Paragraph>
                            </ContentCard>
                        )}

                        {versaoSelecionada.escopo != null && (
                            <ContentCard
                                title="Escopo"
                                icon={<List size={ICON_SIZE_MD} aria-hidden />}
                                style={{ marginBottom: 16 }}
                            >
                                <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit' }}>
                                    {String(JSON.stringify(versaoSelecionada.escopo, null, 2))}
                                </pre>
                            </ContentCard>
                        )}

                        {versaoSelecionada.requisitos_principais != null && (
                            <ContentCard
                                title="Requisitos Principais"
                                icon={<SquareCheck size={ICON_SIZE_MD} aria-hidden />}
                                style={{ marginBottom: 16 }}
                            >
                                <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit' }}>
                                    {String(
                                        JSON.stringify(
                                            versaoSelecionada.requisitos_principais,
                                            null,
                                            2
                                        )
                                    )}
                                </pre>
                            </ContentCard>
                        )}

                        {versaoSelecionada.entregaveis != null && (
                            <ContentCard
                                title="Entregáveis"
                                icon={<Box size={ICON_SIZE_MD} aria-hidden />}
                                style={{ marginBottom: 16 }}
                            >
                                <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit' }}>
                                    {String(JSON.stringify(versaoSelecionada.entregaveis, null, 2))}
                                </pre>
                            </ContentCard>
                        )}

                        {versaoSelecionada.observacoes && (
                            <ContentCard
                                title="Observações"
                                icon={<StickyNote size={ICON_SIZE_MD} aria-hidden />}
                            >
                                <Paragraph>{versaoSelecionada.observacoes}</Paragraph>
                            </ContentCard>
                        )}
                    </div>
                )}
            </Modal>
        </ProjetoLayout>
    );
}
