/* global React */
// Formulário do usuário final (Agência 4 Patas).
// Lê e persiste os valores no localStorage do navegador.

const STORAGE_KEY = 'proposta-agencia-4patas-v1';

function useClientForm(defaults) {
  const [data, setData] = React.useState(() => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        const parsed = JSON.parse(stored);
        return { ...defaults, ...parsed };
      }
    } catch (e) {}
    return defaults;
  });

  const update = (key, value) => {
    setData(prev => {
      const next = { ...prev, [key]: value };
      try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); } catch (e) {}
      return next;
    });
  };

  const reset = () => {
    try { localStorage.removeItem(STORAGE_KEY); } catch (e) {}
    setData(defaults);
  };

  return [data, update, reset];
}

function useServicePrices(defaultServices) {
  const STORAGE = STORAGE_KEY + '-services';
  const [services, setServices] = React.useState(() => {
    try {
      const stored = localStorage.getItem(STORAGE);
      if (stored) {
        const parsed = JSON.parse(stored);
        return defaultServices.map((s, i) => ({
          ...s,
          price: parsed[i]?.price ?? s.price,
          priceLabel: parsed[i]?.priceLabel ?? s.priceLabel,
        }));
      }
    } catch (e) {}
    return defaultServices;
  });

  const updateService = (idx, patch) => {
    setServices(prev => {
      const next = prev.map((s, i) => i === idx ? { ...s, ...patch } : s);
      try {
        const toStore = next.map(s => ({ price: s.price, priceLabel: s.priceLabel }));
        localStorage.setItem(STORAGE, JSON.stringify(toStore));
      } catch (e) {}
      return next;
    });
  };

  const resetServices = () => {
    try { localStorage.removeItem(STORAGE); } catch (e) {}
    setServices(defaultServices);
  };

  return [services, updateService, resetServices];
}

// ── UI primitives ───────────────────────────────────────────────────────────

function Field({ label, children, hint }) {
  return (
    <label className="cf-field">
      <span className="cf-label">{label}</span>
      {children}
      {hint && <span className="cf-hint">{hint}</span>}
    </label>
  );
}

function TextInput({ value, onChange, placeholder, disabled }) {
  return (
    <input
      type="text"
      className="cf-input"
      value={value || ''}
      onChange={e => onChange(e.target.value)}
      placeholder={placeholder}
      disabled={disabled}
      readOnly={disabled}
    />
  );
}

function NumberInput({ value, onChange, min = 0, max = 99999, step = 1, prefix }) {
  return (
    <div className="cf-number-wrap">
      {prefix && <span className="cf-prefix">{prefix}</span>}
      <input
        type="number"
        className="cf-input cf-input-num"
        value={value ?? 0}
        min={min}
        max={max}
        step={step}
        onChange={e => onChange(Number(e.target.value) || 0)}
      />
    </div>
  );
}

function Textarea({ value, onChange, rows = 2 }) {
  return (
    <textarea
      className="cf-input cf-textarea"
      value={value || ''}
      rows={rows}
      onChange={e => onChange(e.target.value)}
    />
  );
}

function Section({ title, children, defaultOpen = true }) {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div className={`cf-section ${open ? 'open' : ''}`}>
      <button type="button" className="cf-section-head" onClick={() => setOpen(!open)}>
        <span>{title}</span>
        <span className="cf-chev">{open ? '−' : '+'}</span>
      </button>
      {open && <div className="cf-section-body">{children}</div>}
    </div>
  );
}

// ── Main form ──────────────────────────────────────────────────────────────

function ClientForm({ data, updateField, resetData, services, updateService, resetServices }) {
  const [open, setOpen] = React.useState(true);
  const [confirming, setConfirming] = React.useState(false);

  const handlePrint = () => { window.print(); };

  const handleReset = () => {
    if (confirming) {
      resetData();
      resetServices();
      setConfirming(false);
    } else {
      setConfirming(true);
      setTimeout(() => setConfirming(false), 4000);
    }
  };

  if (!open) {
    return (
      <button className="cf-fab" onClick={() => setOpen(true)} title="Editar proposta">
        ✏️ Editar
      </button>
    );
  }

  return (
    <aside className="cf-panel no-print" role="dialog" aria-label="Editar proposta">
      <header className="cf-head">
        <div>
          <div className="cf-head-title">Editar Proposta</div>
          <div className="cf-head-sub">Preencha os dados do cliente abaixo</div>
        </div>
        <button className="cf-close" onClick={() => setOpen(false)} title="Esconder painel">✕</button>
      </header>

      <div className="cf-body">
        <Section title="📋 Documento">
          <div className="cf-grid-2">
            <Field label="Nº do orçamento">
              <TextInput value={data.docNumber} onChange={v => updateField('docNumber', v)} placeholder="79/2026" />
            </Field>
            <Field label="Data" hint="Preenchida automaticamente (Brasília)">
              <TextInput value={getDataBrasilia()} onChange={() => {}} placeholder="dd/mm/aaaa" disabled />
            </Field>
          </div>
          <Field label="Validade (dias)">
            <NumberInput value={data.validityDays} onChange={v => updateField('validityDays', v)} min={1} max={90} />
          </Field>
        </Section>

        <Section title="👤 Cliente">
          <Field label="Nome do responsável">
            <TextInput value={data.clientName} onChange={v => updateField('clientName', v)} placeholder="André Costa" />
          </Field>
          <Field label="Negócio / nicho">
            <TextInput value={data.clientBusiness} onChange={v => updateField('clientBusiness', v)} placeholder="Controle Adestramento, Educação Canina, Hospedagem e Recreação" />
          </Field>
          <Field label="Cidade / UF / Região">
            <TextInput value={data.clientCity} onChange={v => updateField('clientCity', v)} placeholder="Pelotas / RS e região" />
          </Field>
          <Field label="Telefone / WhatsApp">
            <TextInput value={data.clientPhone} onChange={v => updateField('clientPhone', v)} placeholder="(53) 9 9999-0000" />
          </Field>
        </Section>

        <Section title="💳 Pagamento">
          <Field label="Condições de pagamento">
            <Textarea value={data.paymentTerms} onChange={v => updateField('paymentTerms', v)} rows={2} />
          </Field>
        </Section>

        <Section title="💰 Preços dos Serviços" defaultOpen={false}>
          {services.map((s, i) => (
            <div className="cf-service" key={s.id}>
              <div className="cf-service-title">{s.title}</div>
              <div className="cf-grid-2">
                <Field label="Valor (R$)">
                  <NumberInput
                    value={s.price}
                    onChange={v => updateService(i, { price: v })}
                    min={0}
                    max={50000}
                    step={50}
                    prefix="R$"
                  />
                </Field>
                <Field label='Texto custom (ex: "Gratuita")'>
                  <TextInput
                    value={s.priceLabel}
                    onChange={v => updateService(i, { priceLabel: v })}
                    placeholder="(opcional)"
                  />
                </Field>
              </div>
            </div>
          ))}
        </Section>
      </div>

      <footer className="cf-foot">
        <button
          className={`cf-btn cf-btn-ghost ${confirming ? 'confirming' : ''}`}
          onClick={handleReset}
          title="Limpa todos os campos para começar uma nova proposta"
        >
          {confirming ? '⚠ Confirmar limpeza?' : '🗑 Nova Proposta'}
        </button>
        <button
          className="cf-btn cf-btn-primary"
          onClick={handlePrint}
          title="Abre a janela de impressão para salvar como PDF"
        >
          📄 Gerar PDF
        </button>
      </footer>
    </aside>
  );
}

window.ClientForm = ClientForm;
window.useClientForm = useClientForm;
window.useServicePrices = useServicePrices;
