'use client';
import { useState } from 'react';

interface TextRow { label: string; value: string; }

interface TextFillFormProps {
  onChange: (data: Record<string, string>) => void;
}

export function TextFillForm({ onChange }: TextFillFormProps) {
  const [rows, setRows] = useState<TextRow[]>([{ label: '', value: '' }]);

  function updateRow(index: number, field: 'label' | 'value', val: string) {
    const next = rows.map((r, i) => i === index ? { ...r, [field]: val } : r);
    setRows(next);
    onChange(Object.fromEntries(next.filter(r => r.label).map(r => [r.label, r.value])));
  }

  function addRow() {
    if (rows.length >= 10) return;
    setRows([...rows, { label: '', value: '' }]);
  }

  function removeRow(index: number) {
    const next = rows.filter((_, i) => i !== index);
    setRows(next.length ? next : [{ label: '', value: '' }]);
    onChange(Object.fromEntries(next.filter(r => r.label).map(r => [r.label, r.value])));
  }

  return (
    <div className="space-y-2">
      <p className="text-xs text-gray-500">
        Field label = AcroForm field name in the PDF (e.g. &quot;PropertyAddress&quot;). Leave blank to skip.
      </p>
      {rows.map((row, i) => (
        <div key={i} className="flex gap-2 items-center">
          <input
            placeholder="Field label"
            value={row.label}
            onChange={e => updateRow(i, 'label', e.target.value)}
            className="flex-1 border rounded px-2 py-1 text-sm"
          />
          <input
            placeholder="Value"
            value={row.value}
            onChange={e => updateRow(i, 'value', e.target.value)}
            className="flex-1 border rounded px-2 py-1 text-sm"
          />
          <button
            onClick={() => removeRow(i)}
            className="text-red-400 hover:text-red-600 text-sm px-1"
            aria-label="Remove row"
            type="button"
          >&times;</button>
        </div>
      ))}
      {rows.length < 10 && (
        <button
          onClick={addRow}
          className="text-blue-600 hover:text-blue-800 text-sm"
          type="button"
        >
          + Add field
        </button>
      )}
    </div>
  );
}
