import {
  App,
  Card,
  Col,
  DatePicker,
  Divider,
  Form,
  Input,
  Modal,
  Row,
  Space,
  Spin,
  Tag,
  Tooltip,
  Typography,
} from 'antd';
import { MailOutlined, PhoneOutlined, WhatsAppOutlined } from '@ant-design/icons';
import type { Contato } from '@sar/api-interface';
import { useClientContacts, useCreateContato } from '../../lib/queries/clients';

const { Text } = Typography;

function ContactActions({ contato }: { contato: Contato }) {
  const wa = contato.whatsapp?.trim() || contato.celular?.trim();
  const tel = contato.telefone?.trim();
  const mail = contato.email?.trim();

  return (
    <Space size={4} wrap>
      {wa && (
        <Tooltip title={`WhatsApp: ${wa}`}>
          <a href={`https://wa.me/55${wa.replace(/\D/g, '')}`} target="_blank" rel="noreferrer">
            <Tag
              icon={<WhatsAppOutlined />}
              color="#25D366"
              style={{ cursor: 'pointer', margin: 0 }}
            >
              {wa}
            </Tag>
          </a>
        </Tooltip>
      )}
      {tel && !wa && (
        <Tooltip title={`Telefone: ${tel}`}>
          <Tag icon={<PhoneOutlined />} color="blue" style={{ margin: 0 }}>
            {tel}
          </Tag>
        </Tooltip>
      )}
      {mail && (
        <Tooltip title={mail}>
          <a href={`mailto:${mail}`}>
            <Tag icon={<MailOutlined />} color="default" style={{ margin: 0 }}>
              {mail.length > 22 ? mail.slice(0, 20) + '…' : mail}
            </Tag>
          </a>
        </Tooltip>
      )}
    </Space>
  );
}

interface Props {
  idCliente: number;
  modalOpen?: boolean;
  onModalClose?: () => void;
}

export function ClientContacts({ idCliente, modalOpen = false, onModalClose }: Props) {
  const { message } = App.useApp();
  const open = modalOpen;
  const setOpen = (v: boolean) => {
    if (!v) onModalClose?.();
  };
  const [form] = Form.useForm();

  const { data: contacts = [], isLoading } = useClientContacts(idCliente);
  const createMutation = useCreateContato(idCliente);

  async function handleSave() {
    const values = await form.validateFields();
    const payload = {
      nome: String(values.nome),
      empresa: values.empresa || undefined,
      cargo: values.cargo || undefined,
      departamento: values.departamento || undefined,
      dtAniversario: values.dtAniversario
        ? (values.dtAniversario as { format: (f: string) => string }).format('YYYY-MM-DD')
        : undefined,
      telefone: values.telefone || undefined,
      celular: values.celular || undefined,
      whatsapp: values.whatsapp || undefined,
      email: values.email || undefined,
      anotacoes: values.anotacoes || undefined,
    };

    let result: Awaited<ReturnType<typeof createMutation.mutateAsync>>;
    try {
      result = await createMutation.mutateAsync(payload);
    } catch {
      return; // erro já notificado pelo handler global do QueryClient; modal fica aberto
    }

    if (!result.sincronizado && result.erroSync) {
      void message.warning(`Contato salvo, mas não sincronizou com ERP: ${result.erroSync}`);
    } else {
      void message.success(`Contato cadastrado! Código ERP: ${result.idContatoErp ?? '—'}`);
    }
    setOpen(false);
    form.resetFields();
  }

  return (
    <>
      <Divider titlePlacement="left" style={{ marginBottom: 12 }}>
        Contatos
      </Divider>

      {isLoading ? (
        <Spin style={{ display: 'block', margin: '16px auto' }} />
      ) : contacts.length === 0 ? (
        <Typography.Text
          type="secondary"
          style={{ display: 'block', marginBottom: 24, textAlign: 'center' }}
        >
          Nenhum contato cadastrado.
        </Typography.Text>
      ) : (
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gap: 12,
            marginBottom: 24,
          }}
        >
          {contacts.map((c: Contato) => (
            <Card
              key={c.idContato}
              size="small"
              styles={{ body: { padding: '10px 12px' } }}
              style={{ borderRadius: 8 }}
            >
              <Text strong style={{ fontSize: 13, display: 'block', marginBottom: 2 }}>
                {c.nome}
              </Text>
              {(c.cargo || c.departamento) && (
                <Text type="secondary" style={{ fontSize: 11, display: 'block', marginBottom: 6 }}>
                  {[c.cargo, c.departamento].filter(Boolean).join(' · ')}
                </Text>
              )}
              <ContactActions contato={c} />
              {c.dtAniversario && (
                <Text type="secondary" style={{ fontSize: 11, display: 'block', marginTop: 4 }}>
                  Aniversário: {new Date(c.dtAniversario + 'T12:00:00').toLocaleDateString('pt-BR')}
                </Text>
              )}
            </Card>
          ))}
        </div>
      )}

      <Modal
        title="Novo Contato"
        open={open}
        onOk={() => void handleSave()}
        onCancel={() => {
          setOpen(false);
          form.resetFields();
        }}
        confirmLoading={createMutation.isPending}
        okText="Cadastrar"
        cancelText="Cancelar"
        width={580}
        destroyOnHidden
      >
        <Form form={form} layout="vertical" style={{ marginTop: 16 }} requiredMark="optional">
          <Form.Item
            name="nome"
            label="Nome"
            rules={[{ required: true, message: 'Informe o nome' }]}
          >
            <Input placeholder="Nome do contato" maxLength={100} />
          </Form.Item>

          <Row gutter={12}>
            <Col span={12}>
              <Form.Item name="cargo" label="Cargo">
                <Input placeholder="Comprador, Gerente..." maxLength={100} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="departamento" label="Departamento">
                <Input placeholder="Compras, Financeiro..." maxLength={100} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={12}>
            <Col span={12}>
              <Form.Item name="whatsapp" label="WhatsApp">
                <Input
                  placeholder="48999990000"
                  maxLength={20}
                  prefix={<WhatsAppOutlined style={{ color: '#25D366' }} />}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="celular" label="Celular">
                <Input placeholder="48999990000" maxLength={20} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={12}>
            <Col span={12}>
              <Form.Item name="telefone" label="Telefone fixo">
                <Input placeholder="4833330000" maxLength={20} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="email" label="E-mail">
                <Input placeholder="contato@empresa.com.br" maxLength={150} type="email" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={12}>
            <Col span={12}>
              <Form.Item name="dtAniversario" label="Aniversário">
                <DatePicker
                  format="DD/MM/YYYY"
                  style={{ width: '100%' }}
                  placeholder="dd/mm/aaaa"
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="anotacoes" label="Anotações">
            <Input.TextArea rows={2} placeholder="Observações sobre o contato..." />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
