import { Card, Flex, Progress, Skeleton, Table, Tag, Typography } from 'antd';
import type { TableColumnsType } from 'antd';
import type { RepStats } from '@sar/api-interface';
import { useEquipe } from '../../lib/queries/gerente';

const { Title, Text } = Typography;

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

const columns: TableColumnsType<RepStats> = [
  {
    title: 'Representante',
    key: 'rep',
    render: (_: unknown, row: RepStats) => (
      <Flex vertical gap={0}>
        <Text strong>{row.nomeVendedor ?? `Cód. ${row.codVendedor}`}</Text>
        {row.nomeVendedor && (
          <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
            cód. {row.codVendedor}
          </Text>
        )}
      </Flex>
    ),
  },
  {
    title: 'Pedidos',
    dataIndex: 'pedidosMes',
    width: 90,
    align: 'right',
    className: 'tabular-nums',
    sorter: (a, b) => a.pedidosMes - b.pedidosMes,
    render: (v: number) => (v === 0 ? <Tag>0</Tag> : v),
  },
  {
    title: 'Faturamento',
    dataIndex: 'faturamentoMes',
    width: 160,
    align: 'right',
    className: 'tabular-nums',
    sorter: (a, b) => a.faturamentoMes - b.faturamentoMes,
    defaultSortOrder: 'descend',
    render: (v: number) => fmt(v),
  },
  {
    title: 'Ticket Medio',
    dataIndex: 'ticketMedio',
    width: 140,
    align: 'right',
    className: 'tabular-nums',
    sorter: (a, b) => a.ticketMedio - b.ticketMedio,
    render: (v: number) => (v > 0 ? fmt(v) : <Text type="secondary">--</Text>),
  },
  {
    title: '% Meta',
    dataIndex: 'pctMeta',
    width: 170,
    sorter: (a, b) => a.pctMeta - b.pctMeta,
    render: (pct: number) =>
      pct === 0 ? (
        <Text type="secondary">sem meta</Text>
      ) : (
        <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>
      ),
  },
];

export function EquipePage() {
  const { data, isLoading } = useEquipe();

  if (isLoading || !data) {
    return (
      <Flex vertical gap={24} style={{ maxWidth: 1280, margin: '0 auto' }}>
        <Skeleton active paragraph={{ rows: 1 }} />
        <Skeleton active paragraph={{ rows: 6 }} />
      </Flex>
    );
  }

  const mes = new Date().toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' });

  return (
    <Flex vertical gap={24} style={{ maxWidth: 1280, margin: '0 auto' }}>
      <Flex vertical gap={4}>
        <Title level={2} style={{ margin: 0 }}>
          Equipe
        </Title>
        <Text type="secondary" style={{ fontSize: 'var(--text-lg)' }}>
          Performance dos representantes &mdash; {mes}
        </Text>
      </Flex>

      <Card>
        <Table<RepStats>
          rowKey="codVendedor"
          columns={columns}
          dataSource={data.reps}
          pagination={false}
          size="small"
          locale={{ emptyText: 'Nenhum representante encontrado.' }}
          scroll={{ x: 700 }}
        />
      </Card>

      <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
        Sync: {new Date(data.syncedAt).toLocaleTimeString('pt-BR')}
      </Text>
    </Flex>
  );
}
