import { Badge, Card, Col, Flex, Row, Skeleton, Space, Table, Tag, Typography } from 'antd';
import type { TableColumnsType } from 'antd';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faCheckCircle,
  faCircleExclamation,
  faClipboardList,
} from '@fortawesome/free-solid-svg-icons';
import { Link } from '@tanstack/react-router';
import type { PedidoSummary } from '@sar/api-interface';
import { useSupervisorDashboard } from '../../lib/queries/dashboard';
import { useCurrentUser } from '../../lib/queries/auth';

const { Title, Text } = Typography;

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

function hoursWaiting(createdAt: string): number {
  return Math.floor((Date.now() - new Date(createdAt).getTime()) / 3_600_000);
}

function delta(current: number, previous: number): { label: string; positive: boolean } | null {
  if (previous === 0) return null;
  const pct = Math.round(((current - previous) / previous) * 100);
  return { label: `${pct >= 0 ? '+' : ''}${pct}% vs semana passada`, positive: pct >= 0 };
}

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', { weekday: 'long', day: 'numeric', month: 'long' });
}

const queueColumns: TableColumnsType<PedidoSummary> = [
  {
    title: 'Pedido',
    dataIndex: 'numPedSar',
    width: 120,
    render: (num: string, row: PedidoSummary) => (
      <Link to="/pedidos/$id" params={{ id: row.id }}>
        {num}
      </Link>
    ),
  },
  {
    title: 'Representante',
    key: 'rep',
    width: 150,
    render: (_: unknown, row: PedidoSummary) => row.nomeVendedor ?? `Cód. ${row.codVendedor}`,
  },
  {
    title: 'Cliente',
    key: 'cliente',
    width: 180,
    render: (_: unknown, row: PedidoSummary) =>
      row.razaoCliente ?? row.nomeCliente ?? `Cód. ${row.idCliente}`,
  },
  {
    title: 'Total',
    dataIndex: 'total',
    width: 130,
    align: 'right',
    render: (v: string) => fmt(Number(v)),
  },
  {
    title: 'Aguardando',
    dataIndex: 'createdAt',
    width: 120,
    render: (v: string) => {
      const h = hoursWaiting(v);
      return <Tag color={h > 2 ? 'red' : 'orange'}>{h}h</Tag>;
    },
  },
  {
    title: '',
    width: 90,
    render: (_: unknown, row: PedidoSummary) => (
      <Link to="/pedidos/$id" params={{ id: row.id }}>
        <Tag color="blue" style={{ cursor: 'pointer' }}>
          Analisar
        </Tag>
      </Link>
    ),
  },
];

export function SupervisorPainel() {
  const { data, isLoading } = useSupervisorDashboard();
  const { data: user } = useCurrentUser();

  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].map((i) => (
            <Col key={i} xs={24} md={8}>
              <Skeleton active />
            </Col>
          ))}
        </Row>
      </Flex>
    );
  }

  const { approvalQueue, pedidosDia, inativosPorRep, syncedAt } = data;
  const urgentCount = approvalQueue.filter((o) => hoursWaiting(o.createdAt) > 2).length;
  const countDelta = delta(pedidosDia.count, pedidosDia.countSemanaAnterior);
  const totalDelta = delta(pedidosDia.total, pedidosDia.totalSemanaAnterior);

  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()}
          {urgentCount > 0 && (
            <>
              {' '}
              ·{' '}
              <span style={{ color: '#cf1322' }}>
                {urgentCount} aprovação{urgentCount > 1 ? 'ões' : ''} urgente
                {urgentCount > 1 ? 's' : ''}
              </span>
            </>
          )}
        </Text>
      </Flex>

      {/* KPIs */}
      <Row gutter={[24, 24]}>
        <Col xs={24} md={8}>
          <Card>
            <Space orientation="vertical" size={4}>
              <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                APROVAÇÕES PENDENTES
              </Text>
              <Flex align="center" gap={8}>
                <Title level={3} style={{ margin: 0 }} className="tabular-nums">
                  {approvalQueue.length}
                </Title>
                {urgentCount > 0 && (
                  <Badge
                    count={urgentCount}
                    style={{ backgroundColor: '#cf1322' }}
                    title={`${urgentCount} urgente(s) — mais de 2h`}
                  />
                )}
              </Flex>
              <Link to="/aprovacoes">
                <Text style={{ fontSize: 'var(--text-sm)', color: 'var(--jcs-blue)' }}>
                  Ver fila completa →
                </Text>
              </Link>
            </Space>
          </Card>
        </Col>

        <Col xs={24} md={8}>
          <Card>
            <Space orientation="vertical" size={4}>
              <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                PEDIDOS HOJE
              </Text>
              <Title level={3} style={{ margin: 0 }} className="tabular-nums">
                {pedidosDia.count}
              </Title>
              {countDelta && (
                <Text
                  style={{
                    fontSize: 'var(--text-sm)',
                    color: countDelta.positive ? 'var(--green)' : '#cf1322',
                  }}
                >
                  {countDelta.label}
                </Text>
              )}
            </Space>
          </Card>
        </Col>

        <Col xs={24} md={8}>
          <Card>
            <Space orientation="vertical" size={4}>
              <Text type="secondary" style={{ fontSize: 'var(--text-sm)' }}>
                VALOR HOJE
              </Text>
              <Title level={3} style={{ margin: 0 }} className="tabular-nums">
                {fmt(pedidosDia.total)}
              </Title>
              {totalDelta && (
                <Text
                  style={{
                    fontSize: 'var(--text-sm)',
                    color: totalDelta.positive ? 'var(--green)' : '#cf1322',
                  }}
                >
                  {totalDelta.label}
                </Text>
              )}
            </Space>
          </Card>
        </Col>
      </Row>

      {/* Fila de aprovações + Inativos por rep */}
      <Row gutter={[24, 24]}>
        <Col xs={24} lg={16}>
          <Card
            title={
              <Space>
                <FontAwesomeIcon icon={faCheckCircle} style={{ color: 'var(--jcs-blue)' }} />
                Fila de Aprovações
                {approvalQueue.length > 0 && (
                  <Badge
                    count={approvalQueue.length}
                    style={{ backgroundColor: 'var(--jcs-blue)' }}
                  />
                )}
              </Space>
            }
            extra={<Link to="/aprovacoes">Ver todas</Link>}
          >
            <Table<PedidoSummary>
              rowKey="id"
              columns={queueColumns}
              dataSource={approvalQueue.slice(0, 8)}
              pagination={false}
              size="small"
              rowClassName={(row) => (hoursWaiting(row.createdAt) > 2 ? 'row-urgent' : '')}
              locale={{ emptyText: 'Nenhum pedido aguardando aprovação.' }}
            />
            <style>{`.row-urgent td { background: #fff1f0 !important; }`}</style>
          </Card>
        </Col>

        <Col xs={24} lg={8}>
          <Card
            title={
              <Space>
                <FontAwesomeIcon icon={faCircleExclamation} style={{ color: 'var(--orange)' }} />
                Inativos por Rep
              </Space>
            }
            extra={
              <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
                sem compra +30 dias
              </Text>
            }
          >
            {inativosPorRep.length === 0 ? (
              <Text type="secondary">Nenhum inativo no momento.</Text>
            ) : (
              <Flex vertical gap={12}>
                {inativosPorRep.map((r) => (
                  <Flex
                    key={r.codVendedor}
                    justify="space-between"
                    align="center"
                    style={{
                      padding: 'var(--space-sm) var(--space-md)',
                      borderRadius: 12,
                      background: 'var(--bg-surface-alt)',
                    }}
                  >
                    <Space orientation="vertical" size={0}>
                      <Text strong>{r.nomeVendedor ?? `Rep cód. ${r.codVendedor}`}</Text>
                      {r.nomeVendedor && (
                        <Text type="secondary" style={{ fontSize: 'var(--text-xs)' }}>
                          cód. {r.codVendedor}
                        </Text>
                      )}
                    </Space>
                    <Tag
                      color={r.inativosCount >= 3 ? 'orange' : 'default'}
                      className="tabular-nums"
                    >
                      {r.inativosCount} cliente{r.inativosCount > 1 ? 's' : ''}
                    </Tag>
                  </Flex>
                ))}
              </Flex>
            )}
          </Card>

          <Card
            style={{ marginTop: 24 }}
            title={
              <Space>
                <FontAwesomeIcon icon={faClipboardList} style={{ color: 'var(--jcs-blue)' }} />
                Pedidos de Hoje
              </Space>
            }
          >
            <Flex vertical gap={8}>
              <Flex justify="space-between">
                <Text type="secondary">Total de pedidos</Text>
                <Text strong className="tabular-nums">
                  {pedidosDia.count}
                </Text>
              </Flex>
              <Flex justify="space-between">
                <Text type="secondary">Valor consolidado</Text>
                <Text strong className="tabular-nums">
                  {fmt(pedidosDia.total)}
                </Text>
              </Flex>
              {pedidosDia.countSemanaAnterior > 0 && (
                <Flex justify="space-between">
                  <Text type="secondary">Semana passada</Text>
                  <Text type="secondary" className="tabular-nums">
                    {pedidosDia.countSemanaAnterior} · {fmt(pedidosDia.totalSemanaAnterior)}
                  </Text>
                </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')} · atualiza a cada 30s
        </Text>
      </Flex>
    </Flex>
  );
}
