import { useState } from 'react';
import {
  Button,
  Card,
  Col,
  Flex,
  Progress,
  Row,
  Segmented,
  Skeleton,
  Space,
  Table,
  Tag,
  Typography,
} from 'antd';
import type { TableColumnsType } from 'antd';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faArrowTrendUp,
  faBullseye,
  faChartBar,
  faCircleExclamation,
  faClipboardList,
} from '@fortawesome/free-solid-svg-icons';
import { WhatsAppOutlined } from '@ant-design/icons';
import { Link, useNavigate } from '@tanstack/react-router';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  LineElement,
  PointElement,
  Tooltip as ChartTooltip,
  Legend,
} from 'chart.js';
import { Chart } from 'react-chartjs-2';
import type { MetaItem, ClienteNaoPositivado, PedidoSummary, MesAno } from '@sar/api-interface';
import { SITUA_LABEL } from '@sar/api-interface';
import { useRepDashboard } from '../../lib/queries/dashboard';
import { useCurrentUser } from '../../lib/queries/auth';

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  LineElement,
  PointElement,
  ChartTooltip,
  Legend,
);

const { Title, Text } = Typography;

const SITUA_COLOR: Record<number, string> = {
  1: 'warning',
  2: 'processing',
  3: 'error',
  4: 'success',
};

function fmt(v: number): string {
  return v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}

function greeting(): string {
  const h = new Date().getHours();
  if (h < 12) return 'Bom dia';
  if (h < 18) return 'Boa tarde';
  return 'Boa noite';
}

function today(): string {
  return new Date().toLocaleDateString('pt-BR', { day: 'numeric', month: 'long' });
}

function num(v: number, dec = 0): string {
  return v.toLocaleString('pt-BR', { minimumFractionDigits: dec, maximumFractionDigits: dec });
}

function waLink(whatsapp: string): string {
  const digits = whatsapp.replace(/\D/g, '');
  const number = digits.startsWith('55') ? digits : `55${digits}`;
  return `https://wa.me/${number}`;
}

function MetaCell({
  real,
  meta,
  money,
  dec = 0,
}: {
  real: number;
  meta: number;
  money?: boolean;
  dec?: number;
}) {
  const f = (v: number) => (money ? fmt(v) : num(v, dec));
  const ok = meta > 0 && real >= meta;
  return (
    <Space orientation="vertical" size={0} style={{ lineHeight: 1.15 }}>
      <Text strong className="tabular-nums" style={{ color: ok ? 'var(--green)' : undefined }}>
        {f(real)}
      </Text>
      <Text type="secondary" className="tabular-nums" style={{ fontSize: 'var(--text-xs)' }}>
        / {f(meta)}
      </Text>
    </Space>
  );
}

const metaColumns: TableColumnsType<MetaItem> = [
  {
    title: 'Grupo',
    dataIndex: 'rotulo',
    key: 'rotulo',
    fixed: 'left',
    width: 180,
    render: (v: string) => <Text strong>{v}</Text>,
  },
  {
    title: 'Pedidos',
    dataIndex: 'pedidos',
    key: 'pedidos',
    align: 'right',
    width: 80,
    render: (v: number) => <span className="tabular-nums">{num(v)}</span>,
  },
  {
    title: 'Qtde',
    key: 'qtd',
    align: 'right',
    width: 110,
    render: (_: unknown, r: MetaItem) => <MetaCell real={r.qtdReal} meta={r.qtdMeta} />,
  },
  {
    title: 'Peso (kg)',
    key: 'peso',
    align: 'right',
    width: 120,
    render: (_: unknown, r: MetaItem) => <MetaCell real={r.pesoReal} meta={r.pesoMeta} />,
  },
  {
    title: 'Valor',
    key: 'valor',
    align: 'right',
    width: 160,
    render: (_: unknown, r: MetaItem) => <MetaCell real={r.valorReal} meta={r.valorMeta} money />,
  },
  {
    title: 'Fator (R$/kg)',
    key: 'fator',
    align: 'right',
    width: 110,
    render: (_: unknown, r: MetaItem) => <MetaCell real={r.fatorReal} meta={r.fatorMeta} dec={2} />,
  },
  {
    title: '% da meta (valor)',
    key: 'pct',
    align: 'center',
    width: 160,
    render: (_: unknown, r: MetaItem) => (
      <Progress
        percent={Math.min(r.pct, 100)}
        size="small"
        format={() => `${r.pct}%`}
        strokeColor={r.pct >= 100 ? 'var(--green)' : 'var(--jcs-blue)'}
      />
    ),
  },
];

// ─── Gráfico anual ────────────────────────────────────────────────────────────

const MESES = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];

function GraficoAnual({
  dados,
  ano,
  mesAtual,
}: {
  dados: MesAno[];
  ano: number;
  mesAtual: number;
}) {
  const labels = MESES;

  const barColors = dados.map((d) => {
    if (d.mes > mesAtual) return 'rgba(203,213,225,0.5)'; // futuro — cinza claro
    if (d.mes === mesAtual) return d.atingiu ? 'rgba(56,158,13,0.75)' : 'rgba(0,59,142,0.75)'; // mês atual
    return d.atingiu ? 'rgba(56,158,13,0.85)' : 'rgba(0,59,142,0.65)'; // passado
  });

  const borderColors = dados.map((d) => (d.mes === mesAtual ? '#1a1a1a' : 'transparent'));

  const chartData = {
    labels,
    datasets: [
      {
        type: 'bar' as const,
        label: 'Realizado',
        data: dados.map((d) => (d.mes <= mesAtual ? d.valor : null)),
        backgroundColor: barColors,
        borderColor: borderColors,
        borderWidth: dados.map((d) => (d.mes === mesAtual ? 2 : 0)),
        borderRadius: 4,
        order: 2,
      },
      {
        type: 'line' as const,
        label: 'Meta',
        data: dados.map((d) => (d.meta > 0 ? d.meta : null)),
        borderColor: '#f5222d',
        backgroundColor: 'transparent',
        borderWidth: 2,
        borderDash: [5, 4],
        pointRadius: dados.map((d) => (d.meta > 0 ? 4 : 0)),
        pointBackgroundColor: dados.map((d) =>
          d.meta > 0 && d.mes <= mesAtual ? (d.atingiu ? '#52c41a' : '#f5222d') : '#f5222d',
        ),
        order: 1,
        tension: 0.1,
      },
    ],
  };

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    interaction: { mode: 'index' as const, intersect: false },
    plugins: {
      legend: { position: 'top' as const, labels: { boxWidth: 12, font: { size: 11 } } },
      tooltip: {
        callbacks: {
          label: (ctx: { dataset: { label?: string }; parsed: { y: number | null } }) => {
            const val = ctx.parsed.y;
            if (val == null) return '';
            return ` ${ctx.dataset.label}: ${val.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}`;
          },
        },
      },
    },
    scales: {
      x: { grid: { display: false } },
      y: {
        ticks: {
          callback: (v: number | string) =>
            Number(v).toLocaleString('pt-BR', {
              style: 'currency',
              currency: 'BRL',
              notation: 'compact',
            }),
          font: { size: 10 },
        },
        grid: { color: '#f0f0f0' },
      },
    },
  };

  return (
    <Card
      title={
        <Space>
          <FontAwesomeIcon icon={faChartBar} style={{ color: 'var(--jcs-blue)' }} />
          Realizado vs Meta — {ano}
        </Space>
      }
    >
      <div style={{ height: 240 }}>
        <Chart type="bar" data={chartData} options={options} />
      </div>
    </Card>
  );
}

// ─── Não positivados ──────────────────────────────────────────────────────────

type OrdemNP = 'longe' | 'recentes';

function NaoPositivados({ clientes, total }: { clientes: ClienteNaoPositivado[]; total: number }) {
  const navigate = useNavigate();
  const [ordem, setOrdem] = useState<OrdemNP>('longe');
  const [expandido, setExpandido] = useState(false);
  const PAGE = 10;

  const sorted = [...clientes].sort((a, b) => {
    if (ordem === 'longe') {
      return (b.diasSemPedido ?? 999) - (a.diasSemPedido ?? 999);
    }
    // 'recentes': compraram antes primeiro, ordenados por último pedido desc
    if (a.comprouAntes && !b.comprouAntes) return -1;
    if (!a.comprouAntes && b.comprouAntes) return 1;
    const da = a.ultimoPedido ?? '';
    const db = b.ultimoPedido ?? '';
    return db.localeCompare(da);
  });

  const visible = expandido ? sorted : sorted.slice(0, PAGE);
  const restante = total - PAGE;

  const columns: TableColumnsType<ClienteNaoPositivado> = [
    {
      title: 'Cliente',
      key: 'cliente',
      render: (_: unknown, c: ClienteNaoPositivado) => (
        <Text
          strong
          style={{ cursor: 'pointer', color: 'var(--jcs-blue)' }}
          onClick={() =>
            void navigate({ to: '/clientes/$id', params: { id: String(c.idCliente) } })
          }
        >
          {c.razao ?? c.nome}
        </Text>
      ),
    },
    {
      title: 'Último pedido',
      key: 'ultimo',
      width: 160,
      render: (_: unknown, c: ClienteNaoPositivado) => {
        if (!c.comprouAntes) {
          return (
            <Tag color="default" style={{ borderRadius: 20 }}>
              nunca comprou
            </Tag>
          );
        }
        const dias = c.diasSemPedido ?? 999;
        const cor = dias >= 60 ? 'error' : dias >= 30 ? 'warning' : 'default';
        return (
          <Space orientation="vertical" size={0}>
            <Tag color={cor} className="tabular-nums" style={{ borderRadius: 20 }}>
              {dias}d sem pedido
            </Tag>
            {c.ultimoPedido && (
              <Text type="secondary" style={{ fontSize: 11 }}>
                {new Date(c.ultimoPedido).toLocaleDateString('pt-BR')}
              </Text>
            )}
          </Space>
        );
      },
    },
    {
      title: '',
      key: 'acoes',
      width: 96,
      render: (_: unknown, c: ClienteNaoPositivado) => (
        <Space size={6}>
          <Button
            size="small"
            style={{ borderRadius: 6 }}
            onClick={() =>
              void navigate({ to: '/clientes/$id', params: { id: String(c.idCliente) } })
            }
          >
            Ficha
          </Button>
          {c.whatsapp && (
            <Button
              size="small"
              type="primary"
              style={{ borderRadius: 6, background: '#25d366', borderColor: '#25d366' }}
              icon={<WhatsAppOutlined />}
              href={waLink(c.whatsapp)}
              target="_blank"
              rel="noopener noreferrer"
            />
          )}
        </Space>
      ),
    },
  ];

  return (
    <Card
      title={
        <Space>
          <FontAwesomeIcon icon={faCircleExclamation} style={{ color: 'var(--orange)' }} />
          Não positivados no mês
          {total > 0 && (
            <Tag color="orange" style={{ borderRadius: 20, fontWeight: 700 }}>
              {total}
            </Tag>
          )}
        </Space>
      }
      extra={
        <Segmented<OrdemNP>
          size="small"
          value={ordem}
          onChange={setOrdem}
          options={[
            { label: 'Mais longe', value: 'longe' },
            { label: 'Compraram antes', value: 'recentes' },
          ]}
        />
      }
    >
      {clientes.length === 0 ? (
        <Text type="secondary">Todos os clientes já positivados este mês. Ótimo trabalho!</Text>
      ) : (
        <Flex vertical gap={12}>
          <Table<ClienteNaoPositivado>
            rowKey="idCliente"
            columns={columns}
            dataSource={visible}
            size="small"
            pagination={false}
            showHeader={false}
            style={{ borderRadius: 8 }}
          />
          {!expandido && total > PAGE && (
            <Button
              type="link"
              style={{ alignSelf: 'flex-start', padding: 0 }}
              onClick={() => setExpandido(true)}
            >
              Ver mais {restante} cliente{restante !== 1 ? 's' : ''}
            </Button>
          )}
          {expandido && total > PAGE && (
            <Button
              type="link"
              style={{ alignSelf: 'flex-start', padding: 0 }}
              onClick={() => setExpandido(false)}
            >
              Recolher
            </Button>
          )}
        </Flex>
      )}
    </Card>
  );
}

// ─── RepPainel ────────────────────────────────────────────────────────────────

export function RepPainel() {
  const { data, isLoading } = useRepDashboard();
  const { data: user } = useCurrentUser();

  if (isLoading || !data) {
    return (
      <Flex vertical gap={24} style={{ maxWidth: 1280, margin: '0 auto' }}>
        <Skeleton active paragraph={{ rows: 2 }} />
        <Row gutter={[24, 24]}>
          <Col xs={24} md={14}>
            <Skeleton active />
          </Col>
          <Col xs={24} md={10}>
            <Skeleton active />
          </Col>
        </Row>
      </Flex>
    );
  }

  const {
    meta,
    metasPorGrupo = [],
    pedidosMes,
    pedidosRecentes = [],
    naoPositivados = [],
    totalNaoPositivados = 0,
    historicoMensal = [],
    syncedAt,
  } = data;

  const now = new Date();
  const anoAtual = now.getFullYear();
  const mesAtual = now.getMonth() + 1;

  return (
    <Flex vertical gap={24} style={{ maxWidth: 1280, margin: '0 auto' }}>
      {/* Saudação */}
      <Flex vertical gap={4}>
        <Title level={2} style={{ margin: 0 }}>
          {greeting()}, {user?.nome?.split(' ')[0] ?? '...'}
        </Title>
        <Text type="secondary" style={{ fontSize: 'var(--text-lg)' }}>
          {today()}
          {totalNaoPositivados > 0 && (
            <>
              {' '}
              ·{' '}
              <span style={{ color: 'var(--orange)' }}>
                {totalNaoPositivados} clientes sem pedido no mês
              </span>
            </>
          )}
        </Text>
      </Flex>

      {/* Linha 1 — Meta + Pedidos do mês */}
      <Row gutter={[24, 24]}>
        <Col xs={24} md={14}>
          <Card style={{ height: '100%' }}>
            <Flex vertical gap={16}>
              <Flex justify="space-between" align="flex-start">
                <Space orientation="vertical" size={0}>
                  <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                    META DO MÊS
                  </Text>
                  <Title level={3} style={{ margin: 0 }} className="tabular-nums">
                    {fmt(meta.atingido)}
                  </Title>
                  <Text type="secondary">
                    de <span className="tabular-nums">{fmt(meta.total)}</span>
                  </Text>
                </Space>
                <Tag
                  color={meta.pct >= 100 ? 'success' : meta.pct >= 75 ? 'processing' : 'default'}
                >
                  {meta.pct}% atingido
                </Tag>
              </Flex>
              <Progress
                percent={Math.min(meta.pct, 100)}
                showInfo={false}
                strokeColor="var(--jcs-blue)"
                railColor="var(--jcs-blue-light)"
              />
              {meta.falta > 0 ? (
                <Text style={{ fontSize: 'var(--text-md)' }}>
                  Faltam <strong className="tabular-nums">{fmt(meta.falta)}</strong> pra fechar o
                  mês.
                </Text>
              ) : (
                <Text style={{ fontSize: 'var(--text-md)', color: 'var(--green)' }}>
                  Meta batida! Comissão FLEX ativa.
                </Text>
              )}
            </Flex>
          </Card>
        </Col>

        <Col xs={24} md={10}>
          <Card style={{ height: '100%' }}>
            <Space orientation="vertical" size={4}>
              <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                PEDIDOS NO MÊS
              </Text>
              <Title level={3} style={{ margin: 0 }} className="tabular-nums">
                {pedidosMes}
              </Title>
              <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                <FontAwesomeIcon icon={faArrowTrendUp} /> mês corrente
              </Text>
            </Space>
          </Card>
        </Col>
      </Row>

      {/* Metas por Grupo */}
      {metasPorGrupo.length > 0 && (
        <Card
          title={
            <Space>
              <FontAwesomeIcon icon={faBullseye} style={{ color: 'var(--jcs-blue)' }} />
              Metas por Grupo
            </Space>
          }
          extra={
            <Tag color={meta.pct >= 100 ? 'success' : meta.pct >= 75 ? 'processing' : 'default'}>
              {meta.pct}% no valor total
            </Tag>
          }
        >
          <Table<MetaItem>
            rowKey={(r) => String(r.codigo)}
            columns={metaColumns}
            dataSource={metasPorGrupo}
            size="small"
            pagination={false}
            scroll={{ x: 820 }}
            summary={(rows) => {
              const t = rows.reduce(
                (a, r) => ({
                  pedidos: a.pedidos + r.pedidos,
                  qtdReal: a.qtdReal + r.qtdReal,
                  qtdMeta: a.qtdMeta + r.qtdMeta,
                  pesoReal: a.pesoReal + r.pesoReal,
                  pesoMeta: a.pesoMeta + r.pesoMeta,
                  valorReal: a.valorReal + r.valorReal,
                  valorMeta: a.valorMeta + r.valorMeta,
                }),
                {
                  pedidos: 0,
                  qtdReal: 0,
                  qtdMeta: 0,
                  pesoReal: 0,
                  pesoMeta: 0,
                  valorReal: 0,
                  valorMeta: 0,
                },
              );
              const pctTotal = t.valorMeta > 0 ? Math.round((t.valorReal / t.valorMeta) * 100) : 0;
              const fatorReal = t.pesoReal > 0 ? t.valorReal / t.pesoReal : 0;
              const fatorMeta = t.pesoMeta > 0 ? t.valorMeta / t.pesoMeta : 0;
              return (
                <Table.Summary.Row style={{ background: 'var(--bg-surface-alt)' }}>
                  <Table.Summary.Cell index={0}>
                    <Text strong>Total</Text>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={1} align="right">
                    <span className="tabular-nums">{num(t.pedidos)}</span>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={2} align="right">
                    <MetaCell real={t.qtdReal} meta={t.qtdMeta} />
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={3} align="right">
                    <MetaCell real={t.pesoReal} meta={t.pesoMeta} />
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={4} align="right">
                    <MetaCell real={t.valorReal} meta={t.valorMeta} money />
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={5} align="right">
                    <MetaCell real={fatorReal} meta={fatorMeta} dec={2} />
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={6} align="center">
                    <Text strong>{pctTotal}%</Text>
                  </Table.Summary.Cell>
                </Table.Summary.Row>
              );
            }}
          />
        </Card>
      )}

      {/* Gráfico anual */}
      <GraficoAnual dados={historicoMensal} ano={anoAtual} mesAtual={mesAtual} />

      {/* Linha 2 — Não positivados + Pedidos recentes */}
      <Row gutter={[24, 24]}>
        <Col xs={24} lg={14}>
          <NaoPositivados clientes={naoPositivados} total={totalNaoPositivados} />
        </Col>

        <Col xs={24} lg={10}>
          <Card
            title={
              <Space>
                <FontAwesomeIcon icon={faClipboardList} style={{ color: 'var(--jcs-blue)' }} />
                Pedidos recentes
              </Space>
            }
            extra={<Link to="/pedidos">Ver todos</Link>}
          >
            {pedidosRecentes.length === 0 ? (
              <Text type="secondary">Nenhum pedido nos últimos 7 dias.</Text>
            ) : (
              <Flex vertical gap={10}>
                {pedidosRecentes.map((o: PedidoSummary) => (
                  <Flex key={o.id} justify="space-between" align="center">
                    <Space orientation="vertical" size={0}>
                      <Link to="/pedidos/$id" params={{ id: o.id }}>
                        <Text strong className="tabular-nums">
                          {o.numPedSar}
                        </Text>
                      </Link>
                      <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
                        {o.razaoCliente ?? o.nomeCliente ?? `Cód. cliente ${o.idCliente}`}
                      </Text>
                    </Space>
                    <Flex gap={8} align="center">
                      <Text className="tabular-nums" style={{ fontSize: 'var(--text-sm)' }}>
                        {Number(o.total).toLocaleString('pt-BR', {
                          style: 'currency',
                          currency: 'BRL',
                        })}
                      </Text>
                      <Tag color={SITUA_COLOR[o.situa] ?? 'default'}>
                        {SITUA_LABEL[o.situa] ?? String(o.situa)}
                      </Tag>
                    </Flex>
                  </Flex>
                ))}
              </Flex>
            )}
          </Card>
        </Col>
      </Row>

      <Flex justify="space-between" style={{ paddingTop: 8 }}>
        <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
          SAR · Força de Vendas · Powered by JCS Sistemas
        </Text>
        <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
          Sync: {new Date(syncedAt).toLocaleTimeString('pt-BR')}
        </Text>
      </Flex>
    </Flex>
  );
}
