import { useState } from 'react';
import FiscalFieldset, { type FiscalState } from './FiscalFieldset';

interface Contact {
  id: string;
  fullName: string;
  email: string | null;
  whatsapp: string | null;
  lifecycleStage: string;
  rfc: string | null;
  fiscalRegimeCode: string | null;
  cfdiUse: string | null;
  fiscalZipCode: string | null;
  kindOfPerson: string | null;
}
interface SatOption {
  code: string;
  label: string;
}
interface Props {
  contact: Contact;
  companyName: string;
  lifecycleOptions: { value: string; label: string }[];
  regimes: SatOption[];
  cfdiUses: SatOption[];
}

export default function ContactEditor({ contact, companyName, lifecycleOptions, regimes, cfdiUses }: Props) {
  const [fullName, setFullName] = useState(contact.fullName);
  const [email, setEmail] = useState(contact.email ?? '');
  const [whatsapp, setWhatsapp] = useState(contact.whatsapp ?? '');
  const [company, setCompany] = useState(companyName && companyName !== '—' ? companyName : '');
  const [lifecycleStage, setLifecycleStage] = useState(contact.lifecycleStage);
  const [fiscal, setFiscal] = useState<FiscalState>({
    rfc: contact.rfc ?? '',
    fiscalRegimeCode: contact.fiscalRegimeCode ?? '',
    cfdiUse: contact.cfdiUse ?? '',
    fiscalZipCode: contact.fiscalZipCode ?? '',
    kindOfPerson: contact.kindOfPerson ?? '',
  });
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState<{ text: string; ok: boolean } | null>(null);

  function setFiscalField(field: keyof FiscalState, value: string) {
    setFiscal((f) => ({ ...f, [field]: value }));
  }

  async function save() {
    setBusy(true);
    setMsg(null);
    const res = await fetch(`/api/crm/contacts/${contact.id}`, {
      method: 'PATCH',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({
        fullName,
        email: email || null,
        whatsapp: whatsapp || null,
        companyName: company,
        lifecycleStage,
        rfc: fiscal.rfc || null,
        fiscalRegimeCode: fiscal.fiscalRegimeCode || null,
        cfdiUse: fiscal.cfdiUse || null,
        fiscalZipCode: fiscal.fiscalZipCode || null,
        kindOfPerson: fiscal.kindOfPerson || null,
      }),
    });
    const json = await res.json();
    setBusy(false);
    if (json.ok) setMsg({ text: 'Contacto guardado.', ok: true });
    else setMsg({ text: json.error || 'No se pudo guardar.', ok: false });
  }

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      {msg && (
        <p className="notice" style={{ color: msg.ok ? 'var(--pf-success)' : '#ff7a8a' }}>
          {msg.text}
        </p>
      )}

      <div className="card" style={{ padding: 18 }}>
        <h2 style={{ fontSize: '1.1rem' }}>Datos del contacto</h2>
        <div className="field">
          <label>Nombre completo</label>
          <input className="input" value={fullName} onChange={(e) => setFullName(e.target.value)} />
        </div>
        <div className="field">
          <label>Empresa</label>
          <input
            className="input"
            value={company}
            onChange={(e) => setCompany(e.target.value)}
            placeholder="Nombre de la empresa (se crea si no existe)"
          />
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <div className="field" style={{ flex: '1 1 180px' }}>
            <label>Correo</label>
            <input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
          </div>
          <div className="field" style={{ flex: '1 1 160px' }}>
            <label>WhatsApp</label>
            <input className="input" type="tel" value={whatsapp} onChange={(e) => setWhatsapp(e.target.value)} />
          </div>
        </div>
        <div className="field" style={{ marginBottom: 0 }}>
          <label>Etapa de ciclo de vida</label>
          <select className="select" value={lifecycleStage} onChange={(e) => setLifecycleStage(e.target.value)}>
            {!lifecycleOptions.some((o) => o.value === lifecycleStage) && (
              <option value={lifecycleStage}>{lifecycleStage}</option>
            )}
            {lifecycleOptions.map((o) => (
              <option key={o.value} value={o.value}>{o.label}</option>
            ))}
          </select>
        </div>
      </div>

      <FiscalFieldset value={fiscal} onChange={setFiscalField} regimes={regimes} cfdiUses={cfdiUses} />

      <button className="btn btn-primary" disabled={busy} onClick={save}>
        {busy ? 'Guardando…' : 'Guardar contacto'}
      </button>
    </div>
  );
}
