import { useState } from 'react';
import {
  Badge,
  Button,
  Form,
  Input,
  Modal,
  Select,
  Space,
  Spin,
  Table,
  Tag,
  Typography,
  Tabs,
} from 'antd';
import { CustomerServiceOutlined } from '@ant-design/icons';
import type { TableColumnsType } from 'antd';
import {
  STATUS_CHAMADO_LABEL,
  TIPO_CHAMADO_LABEL,
  RESOLUCAO_CHAMADO,
  RESOLUCAO_CHAMADO_LABEL,
  type Chamado,
  type ChamadoMensagem,
  type ItemAfetado,
  type ResolverChamadoDto,
} from '@sar/api-interface';
import {
  useChamadosGer,
  useChamadoGer,
  useAddMensagemEmpresa,
  useResolverChamado,
} from '../../lib/queries/sac';

const { Title, Text } = Typography;
const { TextArea } = Input;

const STATUS_COLOR: Record<string, string> = {
  aberto: 'blue',
  em_analise: 'orange',
  aguardando_rep: 'purple',
  resolvido: 'green',
  cancelado: 'default',
};

function ResolverModal({ id, open, onClose }: { id: number; open: boolean; onClose: () => void }) {
  const [form] = Form.useForm<ResolverChamadoDto>();
  const resolver = useResolverChamado(id);

  function handleOk() {
    form.validateFields().then((values) => {
      resolver.mutate(values, {
        onSuccess: () => {
          form.resetFields();
          onClose();
        },
      });
    });
  }

  return (
    <Modal
      title="Resolver Chamado"
      open={open}
      onOk={handleOk}
      onCancel={() => {
        form.resetFields();
        onClose();
      }}
      okText="Confirmar Resolução"
      cancelText="Voltar"
      confirmLoading={resolver.isPending}
      width={560}
      centered
    >
      <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
        <Form.Item name="resolucao" label="Tipo de Resolução" rules={[{ required: true }]}>
          <Select placeholder="Selecione...">
            {RESOLUCAO_CHAMADO.map((r) => (
              <Select.Option key={r} value={r}>
                {RESOLUCAO_CHAMADO_LABEL[r]}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="notaResolucao" label="Nota / Detalhes">
          <TextArea rows={3} maxLength={1000} showCount />
        </Form.Item>
        <Form.Item name="mensagemFinal" label="Mensagem final para o representante (opcional)">
          <TextArea rows={2} maxLength={500} showCount />
        </Form.Item>
      </Form>
    </Modal>
  );
}

function ChamadoDetalheModal({
  id,
  open,
  onClose,
}: {
  id: number;
  open: boolean;
  onClose: () => void;
}) {
  const [texto, setTexto] = useState('');
  const [resolverOpen, setResolverOpen] = useState(false);
  const { data: chamado, isLoading } = useChamadoGer(id);
  const addMsg = useAddMensagemEmpresa(id);

  function enviar() {
    if (!texto.trim()) return;
    addMsg.mutate({ texto: texto.trim() }, { onSuccess: () => setTexto('') });
  }

  const fechado = chamado && ['resolvido', 'cancelado'].includes(chamado.status);

  return (
    <>
      <Modal
        title={chamado ? `Chamado #${chamado.id} — ${chamado.assunto}` : 'Chamado'}
        open={open}
        onCancel={onClose}
        footer={null}
        width={720}
        centered
      >
        {isLoading || !chamado ? (
          <Spin />
        ) : (
          <Space orientation="vertical" style={{ width: '100%' }} size="middle">
            <Space wrap>
              <Tag color={STATUS_COLOR[chamado.status]}>{STATUS_CHAMADO_LABEL[chamado.status]}</Tag>
              <Tag>{TIPO_CHAMADO_LABEL[chamado.tipo] ?? chamado.tipo}</Tag>
              <Text type="secondary">Rep: {chamado.codVendedor}</Text>
              <Text type="secondary">Cliente: {chamado.nomeCliente ?? chamado.idCliente}</Text>
            </Space>

            <Text type="secondary">{chamado.descricao}</Text>

            {chamado.notaResolucao && (
              <div
                style={{
                  background: '#f6ffed',
                  border: '1px solid #b7eb8f',
                  borderRadius: 6,
                  padding: '8px 12px',
                }}
              >
                <Text strong>Resolução: </Text>
                <Text>{chamado.notaResolucao}</Text>
              </div>
            )}

            {chamado.itensAfetados && chamado.itensAfetados.length > 0 && (
              <div>
                <Text strong>Itens afetados: </Text>
                {(chamado.itensAfetados as ItemAfetado[]).map((it, i) => (
                  <Tag key={`${it.codProduto}-${i}`}>
                    {it.codProduto} — {it.nomeProduto} (Qtd: {it.qtd})
                  </Tag>
                ))}
              </div>
            )}

            <div
              style={{
                border: '1px solid #f0f0f0',
                borderRadius: 8,
                padding: 12,
                maxHeight: 320,
                overflowY: 'auto',
                display: 'flex',
                flexDirection: 'column',
                gap: 8,
              }}
            >
              {(chamado.mensagens ?? []).length === 0 ? (
                <Text
                  type="secondary"
                  style={{ textAlign: 'center', display: 'block', padding: '16px 0' }}
                >
                  Sem mensagens ainda.
                </Text>
              ) : (
                ((chamado.mensagens as ChamadoMensagem[]) ?? []).map((m) => (
                  <div
                    key={m.id}
                    style={{
                      display: 'flex',
                      justifyContent: m.autor === 'empresa' ? 'flex-end' : 'flex-start',
                    }}
                  >
                    <div
                      style={{
                        maxWidth: '72%',
                        background: m.autor === 'empresa' ? '#1677ff' : '#f5f5f5',
                        color: m.autor === 'empresa' ? '#fff' : '#000',
                        borderRadius: 10,
                        padding: '8px 12px',
                        fontSize: 13,
                      }}
                    >
                      <div style={{ fontSize: 11, opacity: 0.7, marginBottom: 2 }}>
                        {m.autor === 'empresa' ? 'Empresa' : 'Representante'}
                      </div>
                      <div>{m.texto}</div>
                      <div style={{ fontSize: 11, opacity: 0.7, marginTop: 4, textAlign: 'right' }}>
                        {new Date(m.createdAt).toLocaleString('pt-BR')}
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>

            {!fechado && (
              <Form layout="vertical">
                <Form.Item label="Resposta">
                  <TextArea
                    rows={2}
                    value={texto}
                    onChange={(e) => setTexto(e.target.value)}
                    maxLength={2000}
                    showCount
                  />
                </Form.Item>
                <Space>
                  <Button
                    type="primary"
                    onClick={enviar}
                    loading={addMsg.isPending}
                    disabled={!texto.trim()}
                  >
                    Responder
                  </Button>
                  <Button
                    type="primary"
                    style={{ backgroundColor: '#52c41a', borderColor: '#52c41a' }}
                    onClick={() => setResolverOpen(true)}
                  >
                    Resolver
                  </Button>
                </Space>
              </Form>
            )}
          </Space>
        )}
      </Modal>

      <ResolverModal id={id} open={resolverOpen} onClose={() => setResolverOpen(false)} />
    </>
  );
}

const columns: TableColumnsType<Chamado> = [
  { title: '#', dataIndex: 'id', width: 60 },
  {
    title: 'Status',
    dataIndex: 'status',
    width: 140,
    render: (s: string) => (
      <Tag color={STATUS_COLOR[s] ?? 'default'}>{STATUS_CHAMADO_LABEL[s] ?? s}</Tag>
    ),
  },
  {
    title: 'Tipo',
    dataIndex: 'tipo',
    width: 160,
    render: (t: string) => TIPO_CHAMADO_LABEL[t] ?? t,
  },
  { title: 'Assunto', dataIndex: 'assunto', ellipsis: true },
  { title: 'Rep', dataIndex: 'codVendedor', width: 70 },
  { title: 'Cliente', dataIndex: 'nomeCliente', width: 160 },
  {
    title: 'Atualizado',
    dataIndex: 'updatedAt',
    width: 110,
    render: (v: string) => new Date(v).toLocaleDateString('pt-BR'),
  },
];

export function GerChamadosPage() {
  const { data, isLoading } = useChamadosGer();
  const [detalheId, setDetalheId] = useState<number | null>(null);

  if (isLoading) return <Spin style={{ display: 'block', marginTop: 64 }} />;

  const abertos = data?.abertos ?? [];
  const fechados = data?.fechados ?? [];

  return (
    <div style={{ padding: 24, maxWidth: 1200, margin: '0 auto' }}>
      <Space align="center" style={{ marginBottom: 24 }}>
        <CustomerServiceOutlined style={{ fontSize: 24, color: '#1677ff' }} />
        <Title level={3} style={{ margin: 0 }}>
          SAC — Chamados da Empresa
        </Title>
        {abertos.length > 0 && <Badge count={abertos.length} />}
      </Space>

      <Tabs
        items={[
          {
            key: 'abertos',
            label: `Abertos (${abertos.length})`,
            children: (
              <Table<Chamado>
                rowKey="id"
                columns={columns}
                dataSource={abertos}
                pagination={false}
                size="small"
                onRow={(r) => ({ onClick: () => setDetalheId(r.id), style: { cursor: 'pointer' } })}
                locale={{ emptyText: 'Nenhum chamado aberto.' }}
              />
            ),
          },
          {
            key: 'fechados',
            label: `Fechados (${fechados.length})`,
            children: (
              <Table<Chamado>
                rowKey="id"
                columns={columns}
                dataSource={fechados}
                pagination={{ pageSize: 20 }}
                size="small"
                onRow={(r) => ({ onClick: () => setDetalheId(r.id), style: { cursor: 'pointer' } })}
                locale={{ emptyText: 'Nenhum chamado fechado.' }}
              />
            ),
          },
        ]}
      />

      {detalheId !== null && (
        <ChamadoDetalheModal
          id={detalheId}
          open={detalheId !== null}
          onClose={() => setDetalheId(null)}
        />
      )}
    </div>
  );
}
