import { useState } from "react";
import { useFormContext } from "react-hook-form";

// Renderiza una propiedad recursivamente con expansión
function DebugField({ label, oldValue, newValue }: { label?: string; oldValue: any; newValue: any }) {
  const [open, setOpen] = useState(false);

  const isObject = typeof newValue === "object" && newValue !== null;

  if (!isObject) {
    return (
      <li className="ml-4">
        {label && <span className="font-medium">{label}: </span>}
        <span className="text-gray-500 line-through">{String(oldValue)}</span>{" "}
        ➝ <span className="text-green-600">{String(newValue)}</span>
      </li>
    );
  }

  return (
    <li className="ml-4">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="text-left font-medium text-blue-600 hover:underline focus:outline-none"
      >
        {open ? "▼" : "▶"} {label}
      </button>
      {open && (
        <ul className="ml-4 border-l pl-2 mt-1 space-y-1">
          {Object.keys(newValue).map((key) => (
            <DebugField
              key={key}
              label={key}
              oldValue={oldValue?.[key]}
              newValue={newValue[key]}
            />
          ))}
        </ul>
      )}
    </li>
  );
}

export const FormDebug = () => {
  const { watch, formState } = useFormContext();
  const { isDirty, dirtyFields, defaultValues } = formState;
  const currentValues = watch();

  return (
    <div className="p-4 border rounded bg-red-50 mb-6">
      <p>
        <strong>¿Formulario modificado?</strong> {isDirty ? "Sí" : "No"}
      </p>
      <div className="mt-2">
        <strong>Campos modificados:</strong>
        {Object.keys(dirtyFields).length > 0 ? (
          <ul className="list-disc list-inside mt-1">
            {Object.keys(dirtyFields).map((key) => (
              <DebugField
                key={key}
                label={key}
                oldValue={defaultValues?.[key]}
                newValue={currentValues[key]}
              />
            ))}
          </ul>
        ) : (
          <p>Ninguno</p>
        )}
      </div>
    </div>
  );
};
