import { useState } from "react";

interface FormField {
  name: string;
  label: string;
  type: "text" | "textarea" | "number" | "select" | "checkbox" | "code";
  value: string | number | boolean;
  options?: { value: string; label: string }[];
  placeholder?: string;
  required?: boolean;
  rows?: number;
}

interface MobileEditViewProps {
  title: string;
  fields?: FormField[];
  onSave: (data: Record<string, string | number | boolean>) => void;
  onCancel: () => void;
  onDelete?: () => void;
  deleteLabel?: string;
  isSaving?: boolean;
  children?: React.ReactNode;
}

export const MobileEditView: React.FC<MobileEditViewProps> = ({
  title,
  fields,
  onSave,
  onCancel,
  onDelete,
  deleteLabel = "Delete",
  isSaving = false,
  children,
}) => {
  const [formData, setFormData] = useState<Record<string, string | number | boolean>>(
    () => {
      const initial: Record<string, string | number | boolean> = {};
      fields?.forEach((field) => {
        initial[field.name] = field.value;
      });
      return initial;
    }
  );

  const handleChange = (name: string, value: string | number | boolean) => {
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave(formData);
  };

  return (
    <div className="mobile-edit-view">
      <header className="mobile-edit-header">
        <button
          className="mobile-edit-cancel"
          onClick={onCancel}
          type="button"
          disabled={isSaving}
        >
          Cancel
        </button>
        <h1 className="mobile-edit-title">{title}</h1>
        <div style={{ width: "4rem" }} />
      </header>

      <form className="mobile-edit-form" onSubmit={handleSubmit}>
        {children || fields?.map((field) => (
          <div key={field.name} className="mobile-edit-field">
            <label className="mobile-edit-field-label" htmlFor={field.name}>
              {field.label}
              {field.required && <span className="required">*</span>}
            </label>

            {field.type === "textarea" && (
              <textarea
                id={field.name}
                name={field.name}
                value={String(formData[field.name] ?? "")}
                onChange={(e) => handleChange(field.name, e.target.value)}
                placeholder={field.placeholder}
                required={field.required}
                rows={field.rows || 4}
                className="mobile-edit-input mobile-edit-textarea"
              />
            )}

            {field.type === "select" && (
              <select
                id={field.name}
                name={field.name}
                value={String(formData[field.name] ?? "")}
                onChange={(e) => handleChange(field.name, e.target.value)}
                required={field.required}
                className="mobile-edit-input"
              >
                {field.options?.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            )}

            {field.type === "checkbox" && (
              <label className="mobile-edit-checkbox">
                <input
                  type="checkbox"
                  id={field.name}
                  name={field.name}
                  checked={Boolean(formData[field.name])}
                  onChange={(e) => handleChange(field.name, e.target.checked)}
                />
                <span>{field.label}</span>
              </label>
            )}

            {field.type === "code" && (
              <textarea
                id={field.name}
                name={field.name}
                value={String(formData[field.name] ?? "")}
                onChange={(e) => handleChange(field.name, e.target.value)}
                placeholder={field.placeholder}
                required={field.required}
                rows={field.rows || 8}
                className="mobile-edit-input mobile-edit-code"
                style={{ fontFamily: "monospace" }}
              />
            )}

            {(field.type === "text" || field.type === "number") && (
              <input
                type={field.type === "number" ? "number" : "text"}
                id={field.name}
                name={field.name}
                value={String(formData[field.name] ?? "")}
                onChange={(e) =>
                  handleChange(
                    field.name,
                    field.type === "number"
                      ? Number(e.target.value)
                      : e.target.value
                  )
                }
                placeholder={field.placeholder}
                required={field.required}
                className="mobile-edit-input"
              />
            )}
          </div>
        ))}
      </form>

      <div className="mobile-edit-actions">
        <button
          className="mobile-edit-save"
          onClick={() => onSave(formData)}
          type="button"
          disabled={isSaving}
        >
          {isSaving ? "Saving..." : "Save"}
        </button>
        {onDelete && (
          <button
            className="mobile-edit-delete"
            onClick={onDelete}
            type="button"
            disabled={isSaving}
          >
            {deleteLabel}
          </button>
        )}
      </div>
    </div>
  );
};
