'use client';

import { useEffect, useState, FormEvent, useRef, ChangeEvent } from 'react';
import Header from '@/components/header';
import Modal from '@/components/modal';
import api from '@/lib/api';
import { Contract, Client, Proposal } from '@/types';

const STATUS_COLORS: Record<string, string> = {
  draft:              'bg-[#EAE4D9] text-[#0E0F12]/60',
  active:             'bg-green-100 text-green-700',
  pending_signature:  'bg-yellow-100 text-yellow-700',
  cancelled:          'bg-red-100 text-red-700',
  terminated:         'bg-orange-100 text-orange-700',
  finished:           'bg-blue-100 text-blue-700',
};
const STATUS_LABELS: Record<string, string> = {
  draft:             'Rascunho',
  active:            'Ativo',
  pending_signature: 'Ag. assinatura',
  cancelled:         'Cancelado',
  terminated:        'Distratado',
  finished:          'Encerrado',
};

const ADJUSTMENT_OPTIONS = ['IPCA', 'IGP-M', 'INPC', 'fixed', 'none'];
const TRIGGER_OPTIONS = [
  { value: 'after_payment', label: 'Após pagamento' },
  { value: 'before_due',    label: 'Antes do vencimento' },
  { value: 'on_sign',       label: 'Na assinatura' },
];

const today = () => new Date().toISOString().slice(0, 10);

const EMPTY_FORM = {
  clientId: '',
  proposalId: '',
  title: '',
  startDate: today(),
  endDate: '',
  adjustmentIndex: 'IPCA',
  billingDay: '5',
  paymentTerms: '30',
  noticeDays: '30',
  invoiceTrigger: 'after_payment',
  notes: '',
};

type Signer = { name: string; email: string; action: 'SIGN' | 'APPROVE' | 'WITNESS' };

const EMPTY_SIGNER: Signer = { name: '', email: '', action: 'SIGN' };

export default function ContratosPage() {
  const [items, setItems] = useState<Contract[]>([]);
  const [clients, setClients] = useState<Client[]>([]);
  const [proposals, setProposals] = useState<Proposal[]>([]);
  const [loading, setLoading] = useState(true);

  // New contract modal
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  // Signature modal
  const [sigOpen, setSigOpen] = useState(false);
  const [sigContract, setSigContract] = useState<Contract | null>(null);
  const [sigDocName, setSigDocName] = useState('');
  const [sigDeadline, setSigDeadline] = useState('');
  const [signers, setSigners] = useState<Signer[]>([{ ...EMPTY_SIGNER }]);
  const [pdfBase64, setPdfBase64] = useState('');
  const [pdfName, setPdfName] = useState('');
  const [autoGenPdf, setAutoGenPdf] = useState(false);
  const [generatingPdf, setGeneratingPdf] = useState(false);
  const [sigSaving, setSigSaving] = useState(false);
  const [sigError, setSigError] = useState('');
  const fileRef = useRef<HTMLInputElement>(null);

  // Per-row action states
  const [activating, setActivating] = useState<string | null>(null);
  const [syncing, setSyncing] = useState<string | null>(null);
  const [cancellingSig, setCancellingSig] = useState<string | null>(null);
  const [viewingPdf, setViewingPdf] = useState<string | null>(null);

  // Distrato modal
  const [termOpen, setTermOpen] = useState(false);
  const [termContract, setTermContract] = useState<Contract | null>(null);
  const [termReason, setTermReason] = useState('');
  const [termDate, setTermDate] = useState('');
  const [termSaving, setTermSaving] = useState(false);
  const [termError, setTermError] = useState('');

  function load() {
    setLoading(true);
    api.get('/contracts').then((r) => setItems(r.data.data ?? r.data)).catch(() => {}).finally(() => setLoading(false));
  }

  useEffect(() => {
    load();
    api.get('/clients').then((r) => setClients(r.data.data ?? r.data)).catch(() => {});
    api.get('/proposals').then((r) => setProposals(r.data.data ?? r.data)).catch(() => {});
  }, []);

  // Só propostas aceitas do cliente selecionado — é delas que vêm os itens do contrato.
  const clientProposals = proposals.filter(
    (p) => p.clientId === form.clientId && p.status === 'accepted',
  );

  function setF(field: string, value: string) { setForm((p) => ({ ...p, [field]: value })); }

  function openModal() {
    setForm({ ...EMPTY_FORM, startDate: today() });
    setError('');
    setOpen(true);
  }

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    if (!form.proposalId) { setError('Selecione uma proposta aceita do cliente.'); return; }
    setError('');
    setSaving(true);
    try {
      const payload: any = {
        startDate:       form.startDate,
        adjustmentIndex: form.adjustmentIndex,
        billingDay:      Number(form.billingDay),
        paymentTerms:    Number(form.paymentTerms),
        noticeDays:      Number(form.noticeDays),
        invoiceTrigger:  form.invoiceTrigger,
      };
      if (form.title)   payload.title   = form.title;
      if (form.endDate) payload.endDate  = form.endDate;
      if (form.notes)   payload.notes    = form.notes;

      await api.post(`/contracts/from-proposal/${form.proposalId}`, payload);
      setOpen(false);
      load();
    } catch (err: any) {
      setError(err.response?.data?.message ?? 'Erro ao salvar contrato');
    } finally {
      setSaving(false);
    }
  }

  async function handleActivate(c: Contract) {
    if (!confirm(`Ativar contrato ${c.number} sem assinatura?`)) return;
    setActivating(c.id);
    try {
      await api.patch(`/contracts/${c.id}/activate`);
      load();
    } catch (err: any) {
      alert(err.response?.data?.message ?? 'Erro ao ativar contrato');
    } finally {
      setActivating(null);
    }
  }

  async function handleSync(c: Contract) {
    setSyncing(c.id);
    try {
      // Find the signature for this contract and sync
      const res = await api.get(`/signatures/contract/${c.id}`);
      const sigs = res.data;
      if (!sigs?.length) { alert('Nenhuma assinatura encontrada para este contrato.'); return; }
      await api.post(`/signatures/${sigs[0].id}/sync`);
      load();
    } catch (err: any) {
      alert(err.response?.data?.message ?? 'Erro ao sincronizar status');
    } finally {
      setSyncing(null);
    }
  }

  async function handleCancelSig(c: Contract) {
    setCancellingSig(c.id);
    try {
      const res = await api.get(`/signatures/contract/${c.id}`);
      const sigs = res.data;
      if (!sigs?.length) { alert('Nenhuma assinatura encontrada para este contrato.'); return; }
      const sig = sigs[0];
      const someoneSigned = (sig.signers ?? []).some((s: any) => s.status === 'signed');
      const warning = someoneSigned
        ? 'Um ou mais signatários já assinaram este documento. Cancelar vai apagá-lo na Autentique e essas assinaturas serão perdidas — quem já assinou vai precisar assinar de novo se você reenviar. Cancelar mesmo assim?'
        : 'Cancelar o envio para assinatura? O documento será apagado na Autentique e o link enviado aos signatários deixará de funcionar.';
      if (!window.confirm(warning)) return;
      await api.post(`/signatures/${sig.id}/cancel`);
      load();
    } catch (err: any) {
      alert(err.response?.data?.message ?? 'Erro ao cancelar envio para assinatura');
    } finally {
      setCancellingSig(null);
    }
  }

  async function handleViewPdf(c: Contract) {
    setViewingPdf(c.id);
    try {
      const res = await api.post(`/contracts/${c.id}/generate-pdf`);
      const byteChars = atob(res.data.pdfBase64);
      const bytes = new Uint8Array(byteChars.length);
      for (let i = 0; i < byteChars.length; i++) bytes[i] = byteChars.charCodeAt(i);
      const blob = new Blob([bytes], { type: 'application/pdf' });
      const url = URL.createObjectURL(blob);
      window.open(url, '_blank');
    } catch (err: any) {
      alert(err.response?.data?.message ?? 'Erro ao gerar o texto do contrato');
    } finally {
      setViewingPdf(null);
    }
  }

  function openTermModal(c: Contract) {
    setTermContract(c);
    setTermReason('');
    setTermDate(today());
    setTermError('');
    setTermOpen(true);
  }

  async function handleTerminate(e: FormEvent) {
    e.preventDefault();
    if (!termContract) return;
    setTermSaving(true);
    setTermError('');
    try {
      await api.patch(`/contracts/${termContract.id}/terminate`, {
        reason: termReason,
        terminationDate: termDate,
      });
      setTermOpen(false);
      load();
    } catch (err: any) {
      setTermError(err.response?.data?.message ?? 'Erro ao realizar distrato');
    } finally {
      setTermSaving(false);
    }
  }

  function openSigModal(c: Contract) {
    setSigContract(c);
    setSigDocName(c.title ? `Contrato ${c.number} — ${c.title}` : `Contrato ${c.number}`);
    setSigDeadline('');
    setSigners([{ ...EMPTY_SIGNER }]);
    setPdfBase64('');
    setPdfName('');
    setAutoGenPdf(false);
    setSigError('');
    setSigOpen(true);
  }

  async function handleGeneratePdf() {
    if (!sigContract) return;
    setGeneratingPdf(true);
    setSigError('');
    try {
      const r = await api.post(`/contracts/${sigContract.id}/generate-pdf`);
      setPdfBase64(r.data.pdfBase64);
      setPdfName(`Contrato_${sigContract.number}.pdf`);
    } catch (err: any) {
      setSigError(err.response?.data?.message ?? 'Erro ao gerar PDF');
      setAutoGenPdf(false);
    } finally {
      setGeneratingPdf(false);
    }
  }

  function handlePdfChange(e: ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setPdfName(file.name);
    const reader = new FileReader();
    reader.onload = () => {
      const result = reader.result as string;
      // strip data:application/pdf;base64, prefix
      const base64 = result.split(',')[1] ?? result;
      setPdfBase64(base64);
    };
    reader.readAsDataURL(file);
  }

  function updateSigner(idx: number, field: keyof Signer, value: string) {
    setSigners((prev) => prev.map((s, i) => i === idx ? { ...s, [field]: value } : s));
  }

  function addSigner() { setSigners((prev) => [...prev, { ...EMPTY_SIGNER }]); }

  function removeSigner(idx: number) {
    setSigners((prev) => prev.filter((_, i) => i !== idx));
  }

  async function handleSendSig(e: FormEvent) {
    e.preventDefault();
    setSigError('');
    if (!pdfBase64) { setSigError('Selecione o PDF do contrato.'); return; }
    if (signers.some((s) => !s.name || !s.email)) { setSigError('Preencha nome e e-mail de todos os signatários.'); return; }

    setSigSaving(true);
    try {
      await api.post('/signatures', {
        contractId:   sigContract!.id,
        pdfBase64,
        documentName: sigDocName,
        deadline:     sigDeadline || undefined,
        signers,
      });
      setSigOpen(false);
      load();
    } catch (err: any) {
      setSigError(err.response?.data?.message ?? 'Erro ao enviar para assinatura');
    } finally {
      setSigSaving(false);
    }
  }

  return (
    <>
      <Header
        title="Contratos"
        subtitle="Gerencie contratos com clientes"
        action={<button className="btn-primary" onClick={openModal}>+ Novo contrato</button>}
      />

      <div className="bg-white rounded-xl border border-[#EAE4D9] overflow-x-auto">
        {loading ? (
          <p className="p-6 text-sm text-[#0E0F12]/50">Carregando...</p>
        ) : items.length === 0 ? (
          <p className="p-6 text-sm text-[#0E0F12]/50">Nenhum contrato criado ainda.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-[#FAF7F2] border-b border-[#EAE4D9]">
              <tr>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Número</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Título</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Início</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Total</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Status</th>
                <th className="px-6 py-3" />
              </tr>
            </thead>
            <tbody className="divide-y divide-[#EAE4D9]">
              {items.map((c) => (
                <tr key={c.id} className="hover:bg-[#FAF7F2]">
                  <td className="px-6 py-3 font-medium text-[#0E0F12]">{c.number}</td>
                  <td className="px-6 py-3 text-[#0E0F12]/50">{c.title ?? '—'}</td>
                  <td className="px-6 py-3 text-[#0E0F12]/50">
                    {c.startDate ? new Date(c.startDate + 'T00:00:00').toLocaleDateString('pt-BR') : '—'}
                  </td>
                  <td className="px-6 py-3 text-[#0E0F12]">R$ {Number(c.total).toFixed(2)}</td>
                  <td className="px-6 py-3">
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_COLORS[c.status] ?? 'bg-[#EAE4D9] text-[#0E0F12]/60'}`}>
                      {STATUS_LABELS[c.status] ?? c.status}
                    </span>
                  </td>
                  <td className="px-6 py-3 text-right">
                    <div className="flex items-center justify-end gap-2">
                      <button
                        onClick={() => handleViewPdf(c)}
                        disabled={viewingPdf === c.id}
                        className="text-xs px-3 py-1.5 rounded-lg border border-[#EAE4D9] text-[#0E0F12]/60 hover:bg-[#FAF7F2] disabled:opacity-50 transition-colors"
                      >
                        {viewingPdf === c.id ? 'Gerando...' : 'Ver contrato'}
                      </button>
                      {c.status === 'draft' && (
                        <>
                          <button
                            onClick={() => openSigModal(c)}
                            className="text-xs px-3 py-1.5 rounded-lg bg-[#0E0F12] text-white hover:bg-[#0E0F12]/80 transition-colors"
                          >
                            Enviar para assinatura
                          </button>
                          <button
                            onClick={() => handleActivate(c)}
                            disabled={activating === c.id}
                            className="text-xs px-3 py-1.5 rounded-lg border border-[#EAE4D9] text-[#0E0F12]/60 hover:bg-[#FAF7F2] disabled:opacity-50 transition-colors"
                          >
                            {activating === c.id ? '...' : 'Ativar'}
                          </button>
                        </>
                      )}
                      {c.status === 'pending_signature' && (
                        <>
                          <button
                            onClick={() => handleSync(c)}
                            disabled={syncing === c.id}
                            className="text-xs px-3 py-1.5 rounded-lg border border-[#EAE4D9] text-[#0E0F12]/60 hover:bg-[#FAF7F2] disabled:opacity-50 transition-colors"
                          >
                            {syncing === c.id ? 'Sincronizando...' : 'Sincronizar status'}
                          </button>
                          <button
                            onClick={() => handleCancelSig(c)}
                            disabled={cancellingSig === c.id}
                            className="text-xs px-3 py-1.5 rounded-lg border border-red-200 text-red-500 hover:bg-red-50 disabled:opacity-50 transition-colors"
                          >
                            {cancellingSig === c.id ? 'Cancelando...' : 'Cancelar envio'}
                          </button>
                        </>
                      )}
                      {c.status === 'active' && (
                        <button
                          onClick={() => openTermModal(c)}
                          className="text-xs px-3 py-1.5 rounded-lg border border-orange-200 text-orange-600 hover:bg-orange-50 transition-colors"
                        >
                          Distrato
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* New contract modal */}
      <Modal open={open} onClose={() => setOpen(false)} title="Novo contrato" wide>
        <form onSubmit={handleSubmit} className="space-y-4">
          {error && <div className="bg-red-50 text-red-700 text-sm px-4 py-3 rounded-lg">{error}</div>}

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Cliente <span className="text-red-500">*</span></label>
            <select
              className="input"
              required
              value={form.clientId}
              onChange={(e) => setForm((p) => ({ ...p, clientId: e.target.value, proposalId: '' }))}
            >
              <option value="">Selecione o cliente...</option>
              {clients.map((cl) => (
                <option key={cl.id} value={cl.id}>{cl.name}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Proposta aceita <span className="text-red-500">*</span></label>
            <select
              className="input"
              required
              disabled={!form.clientId}
              value={form.proposalId}
              onChange={(e) => setF('proposalId', e.target.value)}
            >
              <option value="">
                {form.clientId ? 'Selecione a proposta...' : 'Selecione o cliente primeiro'}
              </option>
              {clientProposals.map((p) => (
                <option key={p.id} value={p.id}>
                  {p.number} — {p.title || 'Proposta'} — R$ {Number(p.total).toFixed(2)}
                </option>
              ))}
            </select>
            {form.clientId && clientProposals.length === 0 && (
              <p className="text-xs text-orange-600 mt-1">
                Este cliente não tem nenhuma proposta aceita. Crie e aceite uma proposta antes de gerar o contrato — é dela que vêm os itens/produtos contratados.
              </p>
            )}
          </div>

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Título (opcional)</label>
            <input className="input" value={form.title} onChange={(e) => setF('title', e.target.value)} placeholder="Ex: Contrato de prestação de serviços" />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Início <span className="text-red-500">*</span></label>
              <input className="input" type="date" required value={form.startDate} onChange={(e) => setF('startDate', e.target.value)} />
            </div>
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Término (opcional)</label>
              <input className="input" type="date" value={form.endDate} onChange={(e) => setF('endDate', e.target.value)} />
            </div>
          </div>

          <div className="border-t border-[#EAE4D9] pt-4">
            <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide mb-3">Cobrança</p>
            <div className="grid grid-cols-3 gap-3">
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Dia de cobrança</label>
                <input className="input" type="number" min="1" max="28" value={form.billingDay} onChange={(e) => setF('billingDay', e.target.value)} />
              </div>
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Prazo pagamento (dias)</label>
                <input className="input" type="number" min="0" value={form.paymentTerms} onChange={(e) => setF('paymentTerms', e.target.value)} />
              </div>
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Emitir NFS-e</label>
                <select className="input" value={form.invoiceTrigger} onChange={(e) => setF('invoiceTrigger', e.target.value)}>
                  {TRIGGER_OPTIONS.map((o) => (
                    <option key={o.value} value={o.value}>{o.label}</option>
                  ))}
                </select>
              </div>
            </div>
          </div>

          <div className="border-t border-[#EAE4D9] pt-4">
            <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide mb-3">Reajuste</p>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Índice</label>
                <select className="input" value={form.adjustmentIndex} onChange={(e) => setF('adjustmentIndex', e.target.value)}>
                  {ADJUSTMENT_OPTIONS.map((o) => <option key={o} value={o}>{o}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Aviso prévio (dias)</label>
                <input className="input" type="number" min="0" value={form.noticeDays} onChange={(e) => setF('noticeDays', e.target.value)} />
              </div>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Observações</label>
            <textarea className="input resize-none" rows={2} value={form.notes} onChange={(e) => setF('notes', e.target.value)} placeholder="Anotações do contrato..." />
          </div>

          <div className="flex justify-end gap-3 pt-2">
            <button type="button" className="btn-secondary" onClick={() => setOpen(false)}>Cancelar</button>
            <button type="submit" className="btn-primary" disabled={saving}>
              {saving ? 'Salvando...' : 'Criar contrato'}
            </button>
          </div>
        </form>
      </Modal>

      {/* Signature modal */}
      <Modal open={sigOpen} onClose={() => setSigOpen(false)} title="Enviar para assinatura" wide>
        <form onSubmit={handleSendSig} className="space-y-4">
          {sigError && <div className="bg-red-50 text-red-700 text-sm px-4 py-3 rounded-lg">{sigError}</div>}

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Nome do documento</label>
            <input className="input" value={sigDocName} onChange={(e) => setSigDocName(e.target.value)} required />
          </div>

          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="block text-sm font-medium text-[#0E0F12]">
                PDF do contrato <span className="text-red-500">*</span>
              </label>
              <label className="flex items-center gap-2 text-xs text-[#0E0F12]/60 cursor-pointer">
                <input
                  type="checkbox"
                  className="h-3.5 w-3.5 rounded accent-[#B7895A]"
                  checked={autoGenPdf}
                  onChange={(e) => {
                    setAutoGenPdf(e.target.checked);
                    if (e.target.checked) {
                      handleGeneratePdf();
                    } else {
                      setPdfBase64('');
                      setPdfName('');
                    }
                  }}
                />
                Gerar automaticamente pelo template
              </label>
            </div>
            {autoGenPdf ? (
              <div className="border border-[#EAE4D9] rounded-lg px-4 py-4 text-center bg-[#FAF7F2]">
                {generatingPdf ? (
                  <p className="text-sm text-[#0E0F12]/50">Gerando PDF...</p>
                ) : pdfName ? (
                  <p className="text-sm text-green-700 font-medium">{pdfName} gerado</p>
                ) : (
                  <p className="text-sm text-red-500">Falha ao gerar PDF</p>
                )}
              </div>
            ) : (
              <>
                <div
                  onClick={() => fileRef.current?.click()}
                  className="border border-dashed border-[#EAE4D9] rounded-lg px-4 py-6 text-center cursor-pointer hover:bg-[#FAF7F2] transition-colors"
                >
                  {pdfName ? (
                    <p className="text-sm text-[#0E0F12]">{pdfName}</p>
                  ) : (
                    <p className="text-sm text-[#0E0F12]/40">Clique para selecionar o PDF</p>
                  )}
                </div>
                <input ref={fileRef} type="file" accept="application/pdf" className="hidden" onChange={handlePdfChange} />
              </>
            )}
          </div>

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Prazo para assinar (opcional)</label>
            <input className="input" type="date" value={sigDeadline} onChange={(e) => setSigDeadline(e.target.value)} />
          </div>

          <div className="border-t border-[#EAE4D9] pt-4">
            <div className="flex items-center justify-between mb-3">
              <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide">Signatários</p>
              <button type="button" onClick={addSigner} className="text-xs text-[#B7895A] hover:underline">
                + Adicionar signatário
              </button>
            </div>
            <div className="space-y-3">
              {signers.map((s, idx) => (
                <div key={idx} className="grid grid-cols-[1fr_1fr_auto_auto] gap-2 items-start">
                  <input
                    className="input"
                    placeholder="Nome"
                    value={s.name}
                    onChange={(e) => updateSigner(idx, 'name', e.target.value)}
                    required
                  />
                  <input
                    className="input"
                    placeholder="E-mail"
                    type="email"
                    value={s.email}
                    onChange={(e) => updateSigner(idx, 'email', e.target.value)}
                    required
                  />
                  <select
                    className="input"
                    value={s.action}
                    onChange={(e) => updateSigner(idx, 'action', e.target.value)}
                  >
                    <option value="SIGN">Assinar</option>
                    <option value="APPROVE">Aprovar</option>
                    <option value="WITNESS">Testemunhar</option>
                  </select>
                  {signers.length > 1 && (
                    <button
                      type="button"
                      onClick={() => removeSigner(idx)}
                      className="text-red-400 hover:text-red-600 px-2 py-2 text-lg leading-none"
                    >
                      ×
                    </button>
                  )}
                </div>
              ))}
            </div>
          </div>

          <div className="flex justify-end gap-3 pt-2">
            <button type="button" className="btn-secondary" onClick={() => setSigOpen(false)}>Cancelar</button>
            <button type="submit" className="btn-primary" disabled={sigSaving}>
              {sigSaving ? 'Enviando...' : 'Enviar para assinatura'}
            </button>
          </div>
        </form>
      </Modal>

      {/* Distrato modal */}
      <Modal open={termOpen} onClose={() => setTermOpen(false)} title={`Distrato — ${termContract?.number ?? ''}`}>
        <form onSubmit={handleTerminate} className="space-y-4">
          {termError && <div className="bg-red-50 text-red-700 text-sm px-4 py-3 rounded-lg">{termError}</div>}

          <p className="text-sm text-[#0E0F12]/60">
            O distrato encerra o contrato de forma consensual. O status será alterado para{' '}
            <span className="font-medium text-orange-600">Distratado</span> e a geração de novas cobranças será interrompida.
          </p>

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">
              Data do distrato <span className="text-red-500">*</span>
            </label>
            <input
              className="input"
              type="date"
              required
              value={termDate}
              onChange={(e) => setTermDate(e.target.value)}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">
              Motivo do distrato <span className="text-red-500">*</span>
            </label>
            <textarea
              className="input resize-none"
              rows={4}
              required
              minLength={5}
              value={termReason}
              onChange={(e) => setTermReason(e.target.value)}
              placeholder="Descreva o motivo do encerramento consensual do contrato..."
            />
          </div>

          <div className="flex justify-end gap-3 pt-2">
            <button type="button" className="btn-secondary" onClick={() => setTermOpen(false)}>Cancelar</button>
            <button type="submit" className="btn-primary bg-orange-500 hover:bg-orange-600 border-orange-500" disabled={termSaving}>
              {termSaving ? 'Registrando...' : 'Confirmar distrato'}
            </button>
          </div>
        </form>
      </Modal>
    </>
  );
}
