import { For, createSignal, Show } from "solid-js";
import type { WidgetConfig, WidgetSettings } from "../types/widget";
import { widgetRegistry } from "../widgets/registry";

interface WidgetConfiguratorProps {
  onAddWidget: (config: WidgetConfig) => void;
}

export function WidgetConfigurator(props: WidgetConfiguratorProps) {
  const [selectedType, setSelectedType] = createSignal<string>("");
  const [settings, setSettings] = createSignal<WidgetSettings>({});
  const [showForm, setShowForm] = createSignal(false);

  const handleTypeSelect = (type: string) => {
    setSelectedType(type);
    setShowForm(true);

    const widget = widgetRegistry[type];
    const defaultSettings: WidgetSettings = {};

    Object.entries(widget.schema.settingsSchema).forEach(([key, schema]) => {
      defaultSettings[key] = schema.default;
    });

    setSettings(defaultSettings);
  };

  const handleSettingChange = (
    key: string,
    value: string | number | boolean,
  ) => {
    setSettings((prev) => ({ ...prev, [key]: value }));
  };

  const handleSubmit = (e: Event) => {
    e.preventDefault();

    const config: WidgetConfig = {
      id: `widget-${Date.now()}`,
      type: selectedType(),
      settings: settings(),
    };

    props.onAddWidget(config);
    setShowForm(false);
    setSelectedType("");
    setSettings({});
  };

  return (
    <div
      style={{
        border: "1px solid var(--border)",
        padding: "1rem",
        "margin-bottom": "1rem",
      }}
    >
      <h2 style={{ "margin-bottom": "1rem" }}>Add Widget</h2>

      <Show when={!showForm()}>
        <div style={{ display: "flex", gap: "0.5rem", "flex-wrap": "wrap" }}>
          <For each={Object.entries(widgetRegistry)}>
            {([type, widget]) => (
              <button onClick={() => handleTypeSelect(type)}>
                + {widget.schema.name}
              </button>
            )}
          </For>
        </div>
      </Show>

      <Show when={showForm()}>
        <div>
          <h3 style={{ "margin-bottom": "0.5rem" }}>
            {widgetRegistry[selectedType()]?.schema.name}
          </h3>
          <p style={{ "margin-bottom": "1rem", color: "var(--gray)" }}>
            {widgetRegistry[selectedType()]?.schema.description}
          </p>

          <form onSubmit={handleSubmit}>
            <For
              each={Object.entries(
                widgetRegistry[selectedType()]?.schema.settingsSchema || {},
              )}
            >
              {([key, schema]) => (
                <div style={{ "margin-bottom": "1rem" }}>
                  <label
                    style={{ display: "block", "margin-bottom": "0.25rem" }}
                  >
                    {schema.label}
                    {schema.required && (
                      <span style={{ color: "var(--gray)" }}> *</span>
                    )}
                  </label>

                  <Show when={schema.type === "string"}>
                    <input
                      type="text"
                      value={settings()[key] as string}
                      onInput={(e) =>
                        handleSettingChange(key, e.currentTarget.value)
                      }
                      required={schema.required}
                      style={{ width: "100%" }}
                    />
                  </Show>

                  <Show when={schema.type === "number"}>
                    <input
                      type="number"
                      value={settings()[key] as number}
                      onInput={(e) =>
                        handleSettingChange(
                          key,
                          parseInt(e.currentTarget.value),
                        )
                      }
                      required={schema.required}
                      style={{ width: "100%" }}
                    />
                  </Show>

                  <Show when={schema.type === "boolean"}>
                    <input
                      type="checkbox"
                      checked={settings()[key] as boolean}
                      onChange={(e) =>
                        handleSettingChange(key, e.currentTarget.checked)
                      }
                    />
                  </Show>

                  <Show when={schema.type === "select" && schema.options}>
                    <select
                      value={settings()[key] as string}
                      onChange={(e) =>
                        handleSettingChange(key, e.currentTarget.value)
                      }
                      required={schema.required}
                      style={{ width: "100%" }}
                    >
                      <For each={schema.options}>
                        {(option) => <option value={option}>{option}</option>}
                      </For>
                    </select>
                  </Show>
                </div>
              )}
            </For>

            <div style={{ display: "flex", gap: "0.5rem" }}>
              <button type="submit">Add Widget</button>
              <button type="button" onClick={() => setShowForm(false)}>
                Cancel
              </button>
            </div>
          </form>
        </div>
      </Show>
    </div>
  );
}
