'use client';

import React from 'react';
import { Spin, Tag } from 'antd';
import { DashboardMetricTitle } from '@/features/dashboard/components/DashboardMetricTitle/DashboardMetricTitle';
import type { DashboardMetricHelpKey } from '@/features/dashboard/dashboardMetricHelp';
import { DashboardSectionDetailLink } from '@/features/dashboard/components/DashboardSectionDetailLink/DashboardSectionDetailLink';
import { DashboardChartCompactFooter } from '@/features/dashboard/components/DashboardChartCompactFooter/DashboardChartCompactFooter';
import styles from './ChartAnalyticCard.module.scss';

export type ChartAnalyticCardProps = {
  /** Texto do título (com `helpKey` ativa MetricHelpIcon). */
  title: React.ReactNode;
  helpKey?: DashboardMetricHelpKey;
  /** Controles extra no header (ex.: Select de período). */
  headerTrailing?: React.ReactNode;
  /** Destino do link "Ver relatório" (desktop) e CTA compacto (mobile). */
  viewDetailsHref?: string;
  viewDetailsSlug?: string;
  /** Resumo numérico ou destaque acima do gráfico. */
  insight?: React.ReactNode;
  /** Legenda ou métricas antes da área principal. */
  legend?: React.ReactNode;
  /** Rodapé após o gráfico (ex.: totais por categoria). */
  footer?: React.ReactNode;
  /** Modo sparkline / mobile denso. */
  compact?: boolean;
  /** Dentro de painel colapsável — oculta chrome duplicado. */
  inCollapse?: boolean;
  loading?: boolean;
  /** Estado vazio quando `hasData` é false. */
  empty?: React.ReactNode;
  hasData?: boolean;
  chartAriaLabel?: string;
  /** Resumo textual só para leitores de tela (ex.: tabela de dados do gráfico). */
  srOnlySummary?: React.ReactNode;
  panelRef?: React.Ref<HTMLDivElement>;
  panelClassName?: string;
  /** `chart` = área plot com empty centralizado; `widget` = corpo flexível (timeline, donuts). */
  bodyVariant?: 'chart' | 'widget';
  bodyClassName?: string;
  children?: React.ReactNode;
  testId?: string;
  /** Sincroniza altura do plot com o `ResponsiveContainer` (px). */
  plotHeight?: number;
};

function panelClassName(compact: boolean, inCollapse: boolean, extra?: string): string {
  return [
    styles.chartPanel,
    compact ? styles.chartPanelCompact : '',
    inCollapse ? styles.chartPanelInCollapse : '',
    extra,
  ]
    .filter(Boolean)
    .join(' ');
}

function plotClassName(compact: boolean): string {
  return [styles.chartPlot, compact ? styles.chartPlotSparkline : ''].filter(Boolean).join(' ');
}

/**
 * Cartão padrão para gráficos analíticos do dashboard (e reutilizável noutros módulos).
 * Centraliza título com ajuda, link "Ver relatório", insight, legenda, empty e modo compacto.
 */
export function ChartAnalyticCard({
  title,
  helpKey,
  headerTrailing,
  viewDetailsHref,
  viewDetailsSlug,
  insight,
  legend,
  footer,
  compact = false,
  inCollapse = false,
  loading = false,
  empty,
  hasData = true,
  chartAriaLabel,
  srOnlySummary,
  panelRef,
  panelClassName: extraPanelClass,
  bodyVariant = 'chart',
  bodyClassName,
  children,
  testId,
  plotHeight,
}: ChartAnalyticCardProps) {
  const showDesktopLink =
    !compact && viewDetailsHref && viewDetailsSlug ? (
      <DashboardSectionDetailLink href={viewDetailsHref} slug={viewDetailsSlug} />
    ) : null;

  const titleNode =
    helpKey !== undefined ? (
      <DashboardMetricTitle helpKey={helpKey}>{title}</DashboardMetricTitle>
    ) : (
      <span>{title}</span>
    );

  const renderBody = () => {
    if (bodyVariant === 'widget') {
      const widgetStyle =
        plotHeight != null
          ? ({ '--chart-analytic-pie-height': `${plotHeight}px` } as React.CSSProperties)
          : undefined;

      const bodyContent = loading ? (
        <div className={styles.loadingPlot} aria-busy="true">
          <Spin />
        </div>
      ) : hasData ? (
        children
      ) : (
        <div className={styles.widgetEmptyBody}>{empty}</div>
      );

      return (
        <div
          className={[styles.widgetBody, bodyClassName].filter(Boolean).join(' ')}
          style={widgetStyle}
        >
          {bodyContent}
        </div>
      );
    }

    const plotContent = loading ? (
      <div className={styles.loadingPlot} aria-busy="true">
        <Spin />
      </div>
    ) : hasData ? (
      <div className={styles.chartPlotInner}>{children}</div>
    ) : (
      <div className={styles.chartEmptyState}>{empty}</div>
    );

    const plotStyle =
      plotHeight != null
        ? ({ '--chart-analytic-plot-height': `${plotHeight}px` } as React.CSSProperties)
        : undefined;

    return (
      <div
        className={plotClassName(compact)}
        style={plotStyle}
        role={chartAriaLabel ? 'img' : undefined}
        aria-label={chartAriaLabel}
      >
        {plotContent}
      </div>
    );
  };

  return (
    <div
      // Cast: externalDir resolve @types/react em front/ e na vertical (tipos incompatíveis).
      ref={panelRef as never}
      className={panelClassName(compact, inCollapse, extraPanelClass)}
      data-testid={testId}
    >
      <div className={styles.sectionTitle}>
        {titleNode}
        <div className={styles.sectionTitleTrailing}>
          {showDesktopLink}
          {headerTrailing}
        </div>
      </div>

      {insight ? <div className={styles.insight}>{insight}</div> : null}
      {legend ? <div className={styles.legend}>{legend}</div> : null}

      {renderBody()}

      {srOnlySummary ? <div className={styles.srOnlySummary}>{srOnlySummary}</div> : null}

      {footer ? <div className={styles.footer}>{footer}</div> : null}

      {compact && viewDetailsHref && viewDetailsSlug ? (
        <DashboardChartCompactFooter href={viewDetailsHref} slug={viewDetailsSlug} />
      ) : null}
    </div>
  );
}

export type ChartAnalyticCardInsightProps = {
  value: React.ReactNode;
  tagLabel?: string;
};

/** Insight típico: valor em destaque + tag (ex. "Total"). */
export function ChartAnalyticCardInsight({ value, tagLabel = 'Total' }: ChartAnalyticCardInsightProps) {
  return (
    <div className={styles.chartSummary}>
      <span className={styles.chartSummaryValue}>{value}</span>
      {tagLabel ? <Tag color="processing">{tagLabel}</Tag> : null}
    </div>
  );
}

export type ChartAnalyticCardFooterStat = {
  label: string;
  value: React.ReactNode;
};

/** Rodapé com colunas de estatísticas (ex. status de projetos). */
export function ChartAnalyticCardFooterStats({ items }: { items: ChartAnalyticCardFooterStat[] }) {
  return (
    <div className={styles.chartFooterStats}>
      {items.map((item) => (
        <div key={item.label}>
          <div className={styles.chartFooterValue}>{item.value}</div>
          <div className={styles.chartFooterLabel}>{item.label}</div>
        </div>
      ))}
    </div>
  );
}

export default ChartAnalyticCard;
