import { useEffect, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Flex,
  InputNumber,
  Progress,
  Row,
  Skeleton,
  Space,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import { useNavigate } from '@tanstack/react-router';
import type { TableColumnsType } from 'antd';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faChartBar,
  faTags,
  faUsers,
  faFileInvoiceDollar,
  faAddressCard,
  faBullseye,
  faArrowTrendUp,
  faCalendarDay,
  faLayerGroup,
} from '@fortawesome/free-solid-svg-icons';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  LineElement,
  PointElement,
  Tooltip as ChartTooltip,
  Legend,
} from 'chart.js';
import { Chart } from 'react-chartjs-2';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import type { RankingRep, PositivacaoRep, PositivacaoDia, MetaItem } from '@sar/api-interface';
import { useManagerDashboard } from '../../lib/queries/gerente';
import { apiFetch } from '../../lib/api-client';

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

const { Title, Text } = Typography;

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

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

const positivacaoColumns: TableColumnsType<PositivacaoRep> = [
  {
    title: 'Representante',
    key: 'rep',
    render: (_: unknown, row: PositivacaoRep) => row.nomeVendedor ?? `Cód. ${row.codVendedor}`,
    ellipsis: true,
  },
  {
    title: 'Positivados / Carteira',
    key: 'pos',
    width: 160,
    align: 'center' as const,
    render: (_: unknown, row: PositivacaoRep) => (
      <Text className="tabular-nums" style={{ fontSize: 'var(--text-sm)' }}>
        {row.clientesPositivados} / {row.totalClientes}
      </Text>
    ),
  },
  {
    title: 'Novos no mês',
    key: 'novos',
    width: 120,
    align: 'center' as const,
    sorter: (a: PositivacaoRep, b: PositivacaoRep) => a.novosClientes - b.novosClientes,
    render: (_: unknown, row: PositivacaoRep) =>
      row.novosClientes > 0 ? (
        <Tag color="green" style={{ margin: 0, fontWeight: 600 }}>
          +{row.novosClientes}
        </Tag>
      ) : (
        <Text type="secondary">—</Text>
      ),
  },
  {
    title: '% Positivação',
    dataIndex: 'pctPositivacao',
    width: 170,
    render: (pct: number) => (
      <Flex align="center" gap={8}>
        <Progress
          percent={Math.min(pct, 100)}
          size="small"
          strokeColor={pct >= 30 ? 'var(--green)' : pct >= 15 ? 'var(--jcs-blue)' : '#faad14'}
          showInfo={false}
          style={{ flex: 1, minWidth: 60 }}
        />
        <Text className="tabular-nums" style={{ fontSize: 'var(--text-sm)', width: 36 }}>
          {pct}%
        </Text>
      </Flex>
    ),
  },
];

const metasGrupoColumns: TableColumnsType<MetaItem> = [
  {
    title: 'Grupo',
    dataIndex: 'rotulo',
    ellipsis: true,
  },
  {
    title: 'Meta',
    dataIndex: 'valorMeta',
    width: 150,
    align: 'right',
    render: (v: number) => fmt(v),
    className: 'tabular-nums',
  },
  {
    title: 'Realizado',
    dataIndex: 'valorReal',
    width: 150,
    align: 'right',
    render: (v: number) => fmt(v),
    className: 'tabular-nums',
  },
  {
    title: 'Falta',
    dataIndex: 'falta',
    width: 130,
    align: 'right',
    render: (v: number) => (
      <Text
        className="tabular-nums"
        style={{ fontSize: 'var(--text-sm)', color: v === 0 ? 'var(--green)' : undefined }}
      >
        {v === 0 ? '—' : fmt(v)}
      </Text>
    ),
  },
  {
    title: '% Meta',
    dataIndex: 'pct',
    width: 170,
    render: (pct: number) => (
      <Flex align="center" gap={8}>
        <Progress
          percent={Math.min(pct, 100)}
          size="small"
          strokeColor={pct >= 100 ? 'var(--green)' : pct >= 70 ? 'var(--jcs-blue)' : '#faad14'}
          showInfo={false}
          style={{ flex: 1, minWidth: 60 }}
        />
        <Text className="tabular-nums" style={{ fontSize: 'var(--text-sm)', width: 48 }}>
          {pct}%
        </Text>
      </Flex>
    ),
  },
];

const rankingColumns: TableColumnsType<RankingRep> = [
  {
    title: 'Representante',
    key: 'rep',
    render: (_: unknown, row: RankingRep) => row.nomeVendedor ?? `Cód. ${row.codVendedor}`,
  },
  {
    title: 'Pedidos',
    dataIndex: 'pedidos',
    width: 80,
    align: 'right',
    className: 'tabular-nums',
  },
  {
    title: 'Clientes',
    dataIndex: 'clientesAtendidos',
    width: 80,
    align: 'right',
    className: 'tabular-nums',
  },
  {
    title: 'Faturamento',
    dataIndex: 'faturamento',
    width: 150,
    align: 'right',
    render: (v: number) => fmt(v),
    className: 'tabular-nums',
  },
  {
    title: '% Meta',
    dataIndex: 'pctMeta',
    width: 160,
    render: (pct: number) => (
      <Flex align="center" gap={8}>
        <Progress
          percent={Math.min(pct, 100)}
          size="small"
          strokeColor={pct >= 100 ? 'var(--green)' : pct >= 70 ? 'var(--jcs-blue)' : '#faad14'}
          showInfo={false}
          style={{ flex: 1, minWidth: 60 }}
        />
        <Text className="tabular-nums" style={{ fontSize: 'var(--text-sm)', width: 36 }}>
          {pct}%
        </Text>
      </Flex>
    ),
  },
];

function PositivacaoDiariaCard({
  dados,
  metaSalva,
  periodo,
  periodoLabel,
  isMesAtual,
}: {
  dados: PositivacaoDia[];
  metaSalva: number;
  periodo: Dayjs;
  periodoLabel: string;
  isMesAtual: boolean;
}) {
  // Meta salva no servidor (config_empresa) — vale em qualquer dispositivo
  const [meta, setMeta] = useState<number>(metaSalva);
  useEffect(() => setMeta(metaSalva), [metaSalva]);
  const qc = useQueryClient();
  const [msg, msgCtx] = message.useMessage();

  const salvarMeta = useMutation({
    mutationFn: (m: number) =>
      apiFetch('/dashboard/manager/meta-positivacao-dia', { method: 'PUT', body: { meta: m } }),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ['dashboard', 'manager'] });
      void msg.success('Meta salva');
    },
  });

  // Eixo com todos os dias: até hoje no mês atual, mês inteiro nos anteriores
  const ultimoDia = isMesAtual ? dayjs().date() : periodo.endOf('month').date();
  const porDia = new Map(dados.map((d) => [dayjs(d.dia).date(), d.clientes]));
  const labels = Array.from({ length: ultimoDia }, (_, i) => String(i + 1));
  const valores = labels.map((d) => porDia.get(Number(d)) ?? 0);
  const diasComMeta = meta > 0 ? valores.filter((v) => v >= meta).length : 0;

  const chartData = {
    labels,
    datasets: [
      {
        type: 'bar' as const,
        label: 'Clientes positivados',
        data: valores,
        backgroundColor: 'rgba(0, 74, 153, 0.8)',
        borderRadius: 4,
        order: 2,
      },
      ...(meta > 0
        ? [
            {
              type: 'line' as const,
              label: `Meta (${meta}/dia)`,
              data: labels.map(() => meta),
              borderColor: '#f5222d',
              backgroundColor: 'transparent',
              borderWidth: 2,
              borderDash: [5, 4],
              pointRadius: 0,
              order: 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: {
          title: (items: { label?: string }[]) => `Dia ${items[0]?.label ?? ''}`,
          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')}`;
          },
        },
      },
    },
    scales: {
      x: { grid: { display: false } },
      y: {
        beginAtZero: true,
        ticks: { precision: 0, font: { size: 10 } },
        grid: { color: '#f0f0f0' },
      },
    },
  };

  return (
    <Card
      title={
        <Space>
          <FontAwesomeIcon icon={faCalendarDay} style={{ color: 'var(--jcs-blue)' }} />
          Positivação Diária de Clientes &mdash; {periodoLabel}
        </Space>
      }
      extra={
        <Flex align="center" gap={8}>
          {meta > 0 && (
            <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
              {diasComMeta} de {ultimoDia} dia{ultimoDia !== 1 ? 's' : ''} na meta
            </Text>
          )}
          <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
            Meta/dia:
          </Text>
          <InputNumber
            min={0}
            size="small"
            value={meta > 0 ? meta : undefined}
            onChange={(v) => setMeta(v ?? 0)}
            placeholder="—"
            style={{ width: 80 }}
          />
          <Button
            type="primary"
            size="small"
            disabled={meta === metaSalva}
            loading={salvarMeta.isPending}
            onClick={() => salvarMeta.mutate(meta)}
          >
            Salvar
          </Button>
        </Flex>
      }
    >
      {msgCtx}
      <div style={{ height: 280 }}>
        <Chart type="bar" data={chartData} options={options} />
      </div>
    </Card>
  );
}

export function GerPainel() {
  const [periodo, setPeriodo] = useState<Dayjs>(dayjs());
  const mes = periodo.month() + 1;
  const ano = periodo.year();

  const { data, isLoading } = useManagerDashboard(mes, ano);
  const navigate = useNavigate();

  const periodoLabel = periodo
    .toDate()
    .toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' });
  const isMesAtual = mes === dayjs().month() + 1 && ano === dayjs().year();

  if (isLoading || !data) {
    return (
      <Flex vertical gap={24} style={{ maxWidth: 1280, margin: '0 auto' }}>
        <Skeleton active paragraph={{ rows: 1 }} />
        <Row gutter={[24, 24]}>
          {[1, 2, 3, 4].map((i) => (
            <Col key={i} xs={24} sm={12} lg={6}>
              <Skeleton active />
            </Col>
          ))}
        </Row>
      </Flex>
    );
  }

  const {
    faturamentoMes,
    pedidosMes,
    ticketMedio,
    totalReps,
    promocoesAtivas,
    metaTotal,
    metasPorGrupo,
    rankingReps,
    positivacaoReps,
    positivacaoDiaria,
    syncedAt,
  } = data;

  const pctMeta = metaTotal > 0 ? Math.round((faturamentoMes / metaTotal) * 100) : 0;
  const faltaMeta = Math.max(0, metaTotal - faturamentoMes);
  const superouMeta = faturamentoMes > metaTotal ? faturamentoMes - metaTotal : 0;
  const metaCorColor =
    pctMeta >= 100 ? 'var(--green)' : pctMeta >= 70 ? 'var(--jcs-blue)' : '#faad14';

  // Dias restantes no período selecionado (incluindo hoje se for mês atual)
  const hoje = dayjs();
  const fimMes = periodo.endOf('month');
  const diasRestantes = isMesAtual
    ? Math.max(0, fimMes.date() - hoje.date() + 1)
    : periodo.isBefore(hoje, 'month')
      ? 0
      : fimMes.date(); // mês futuro: todos os dias
  const vendaPorDia = faltaMeta > 0 && diasRestantes > 0 ? faltaMeta / diasRestantes : 0;

  return (
    <Flex vertical gap={24} style={{ maxWidth: 1280, margin: '0 auto' }}>
      {/* Cabeçalho */}
      <Flex align="flex-start" justify="space-between" wrap="wrap" gap={12}>
        <Flex vertical gap={4}>
          <Title level={2} style={{ margin: 0 }}>
            Painel Gerencial
          </Title>
          <Text type="secondary" style={{ fontSize: 'var(--text-lg)' }}>
            {today()}
          </Text>
        </Flex>

        <Flex align="center" gap={8}>
          <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
            Período:
          </Text>
          <DatePicker
            picker="month"
            value={periodo}
            onChange={(d) => d && setPeriodo(d)}
            format="MMM/YYYY"
            allowClear={false}
            disabledDate={(d) => d.isAfter(dayjs(), 'month')}
            style={{ width: 130 }}
          />
        </Flex>
      </Flex>

      {/* KPIs linha 1 */}
      <Row gutter={[24, 24]}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Flex vertical gap={4}>
              <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                FATURAMENTO {isMesAtual ? 'DO MÊS' : periodoLabel.toUpperCase()}
              </Text>
              <Title level={3} style={{ margin: 0 }} className="tabular-nums">
                {fmt(faturamentoMes)}
              </Title>
              <FontAwesomeIcon
                icon={faFileInvoiceDollar}
                style={{ color: 'var(--jcs-blue)', opacity: 0.5 }}
              />
            </Flex>
          </Card>
        </Col>

        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Flex vertical gap={4}>
              <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                PEDIDOS NO {isMesAtual ? 'MÊS' : 'PERÍODO'}
              </Text>
              <Title level={3} style={{ margin: 0 }} className="tabular-nums">
                {pedidosMes}
              </Title>
              <FontAwesomeIcon
                icon={faChartBar}
                style={{ color: 'var(--jcs-blue)', opacity: 0.5 }}
              />
            </Flex>
          </Card>
        </Col>

        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Flex vertical gap={4}>
              <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                TICKET MÉDIO
              </Text>
              <Title level={3} style={{ margin: 0 }} className="tabular-nums">
                {fmt(ticketMedio)}
              </Title>
              <FontAwesomeIcon icon={faUsers} style={{ color: 'var(--jcs-blue)', opacity: 0.5 }} />
            </Flex>
          </Card>
        </Col>

        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Flex vertical gap={4}>
              <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                PROMOÇÕES ATIVAS
              </Text>
              <Title level={3} style={{ margin: 0 }} className="tabular-nums">
                {promocoesAtivas}
              </Title>
              <FontAwesomeIcon icon={faTags} style={{ color: 'var(--jcs-blue)', opacity: 0.5 }} />
            </Flex>
          </Card>
        </Col>
      </Row>

      {/* KPIs linha 2 — Meta */}
      {metaTotal > 0 && (
        <Row gutter={[24, 24]}>
          <Col xs={24} sm={12} lg={8}>
            <Card>
              <Flex vertical gap={4}>
                <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                  META DO {isMesAtual ? 'MÊS' : 'PERÍODO'}
                </Text>
                <Title level={3} style={{ margin: 0 }} className="tabular-nums">
                  {fmt(metaTotal)}
                </Title>
                <FontAwesomeIcon
                  icon={faBullseye}
                  style={{ color: 'var(--jcs-blue)', opacity: 0.5 }}
                />
              </Flex>
            </Card>
          </Col>

          <Col xs={24} sm={12} lg={8}>
            <Card>
              <Flex vertical gap={8}>
                <Flex justify="space-between" align="center">
                  <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                    ATINGIMENTO DA META
                  </Text>
                  <FontAwesomeIcon
                    icon={faArrowTrendUp}
                    style={{ color: metaCorColor, opacity: 0.7 }}
                  />
                </Flex>
                <Title
                  level={3}
                  style={{ margin: 0, color: metaCorColor }}
                  className="tabular-nums"
                >
                  {pctMeta}%
                </Title>
                <Progress
                  percent={Math.min(pctMeta, 100)}
                  strokeColor={metaCorColor}
                  showInfo={false}
                  size="small"
                />
              </Flex>
            </Card>
          </Col>

          <Col xs={24} sm={12} lg={8}>
            <Card>
              <Flex vertical gap={4}>
                <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                  {superouMeta > 0 ? 'SUPEROU A META EM' : 'FALTA PARA A META'}
                </Text>
                <Title
                  level={3}
                  style={{ margin: 0, color: superouMeta > 0 ? 'var(--green)' : undefined }}
                  className="tabular-nums"
                >
                  {fmt(superouMeta > 0 ? superouMeta : faltaMeta)}
                </Title>
                {superouMeta > 0 ? (
                  <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
                    {pctMeta - 100}% acima da meta
                  </Text>
                ) : vendaPorDia > 0 ? (
                  <Text
                    style={{ fontSize: 'var(--text-xs)', color: metaCorColor, fontWeight: 600 }}
                  >
                    {fmt(vendaPorDia)}/dia &mdash; {diasRestantes} dia
                    {diasRestantes !== 1 ? 's' : ''} restante{diasRestantes !== 1 ? 's' : ''}
                  </Text>
                ) : diasRestantes === 0 ? (
                  <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
                    período encerrado
                  </Text>
                ) : null}
              </Flex>
            </Card>
          </Col>
        </Row>
      )}

      {/* Metas por Grupo */}
      {metasPorGrupo.length > 0 && (
        <Card
          title={
            <Space>
              <FontAwesomeIcon icon={faLayerGroup} style={{ color: 'var(--jcs-blue)' }} />
              Metas por Grupo &mdash; {periodoLabel}
            </Space>
          }
          extra={
            <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
              {metasPorGrupo.filter((g: MetaItem) => g.pct >= 100).length} de {metasPorGrupo.length}{' '}
              grupo
              {metasPorGrupo.length !== 1 ? 's' : ''} atingido
              {metasPorGrupo.filter((g: MetaItem) => g.pct >= 100).length !== 1 ? 's' : ''}
            </Text>
          }
        >
          <Table<MetaItem>
            rowKey={(r) => String(r.codigo ?? r.rotulo)}
            columns={metasGrupoColumns}
            dataSource={metasPorGrupo}
            pagination={false}
            size="small"
            locale={{ emptyText: 'Nenhuma meta por grupo cadastrada.' }}
          />
        </Card>
      )}

      {/* Ranking */}
      <Card
        title={
          <Space>
            <FontAwesomeIcon icon={faChartBar} style={{ color: 'var(--jcs-blue)' }} />
            Ranking de Representantes &mdash; {periodoLabel}
          </Space>
        }
        extra={
          <Flex align="center" gap={12}>
            <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
              top 10 de {totalReps} rep{totalReps !== 1 ? 's' : ''} com pedidos
            </Text>
            <Button size="small" onClick={() => void navigate({ to: '/ger/equipe' })}>
              Ver todos
            </Button>
          </Flex>
        }
      >
        <Table<RankingRep>
          rowKey="codVendedor"
          columns={rankingColumns}
          dataSource={rankingReps}
          pagination={false}
          size="small"
          locale={{ emptyText: 'Nenhum pedido registrado neste período.' }}
        />
      </Card>

      {/* Positivação Diária */}
      <PositivacaoDiariaCard
        dados={positivacaoDiaria}
        metaSalva={data.metaPositivacaoDia ?? 0}
        periodo={periodo}
        periodoLabel={periodoLabel}
        isMesAtual={isMesAtual}
      />

      {/* Positivação por Representante */}
      <Card
        title={
          <Space>
            <FontAwesomeIcon icon={faAddressCard} style={{ color: 'var(--jcs-blue)' }} />
            Positivação de Clientes por Representante &mdash; {periodoLabel}
          </Space>
        }
        extra={
          <Flex align="center" gap={12}>
            {positivacaoReps.reduce((acc, r) => acc + r.novosClientes, 0) > 0 && (
              <Tag color="green" style={{ margin: 0, fontWeight: 600 }}>
                +{positivacaoReps.reduce((acc, r) => acc + r.novosClientes, 0)} novo
                {positivacaoReps.reduce((acc, r) => acc + r.novosClientes, 0) !== 1 ? 's' : ''}{' '}
                cliente
                {positivacaoReps.reduce((acc, r) => acc + r.novosClientes, 0) !== 1 ? 's' : ''} no
                período
              </Tag>
            )}
            <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
              {positivacaoReps.filter((r) => r.clientesPositivados > 0).length} reps com positivação
            </Text>
          </Flex>
        }
      >
        <Table<PositivacaoRep>
          rowKey="codVendedor"
          columns={positivacaoColumns}
          dataSource={positivacaoReps}
          pagination={{ pageSize: 10, size: 'small', showSizeChanger: false }}
          size="small"
          locale={{ emptyText: 'Nenhum dado de carteira encontrado.' }}
        />
      </Card>

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