import type { CatalogEntry } from "../editorCore";

type ConfigSectionProps = {
  activeConfigTab: string;
  activeConfigKey: string;
  activeConfigEntries: CatalogEntry[];
  selectedConfigIndex: number;
  selectedConfigEntry: CatalogEntry | null;
  rootKeys: string[];
  typeLabels: Record<string, string>;
  getCatalogEntryIdValue: (entry: CatalogEntry | null | undefined, fallback?: string) => string;
  normalizeStringList: (value: unknown) => string[];
  parseCsv: (value: string) => string[];
  getContentFieldKeysByType: (type: string) => string[];
  onSetSelectedConfigIndex: (index: number) => void;
  onUpdateActiveConfigEntry: (entryIndex: number, patch: Partial<CatalogEntry>) => void;
};

export default function ConfigSection(props: ConfigSectionProps) {
  const {
    activeConfigTab,
    activeConfigKey,
    activeConfigEntries,
    selectedConfigIndex,
    selectedConfigEntry,
    rootKeys,
    typeLabels,
    getCatalogEntryIdValue,
    normalizeStringList,
    parseCsv,
    getContentFieldKeysByType,
    onSetSelectedConfigIndex,
    onUpdateActiveConfigEntry,
  } = props;

  const isColorsTab = activeConfigTab === "Colors";

  if (isColorsTab) {
    const selectedColor = selectedConfigEntry;
    return (
      <div className="structured-layout">
        <aside className="record-list-panel">
          <h2>{activeConfigTab}</h2>
          <div className="record-list">
            <button
              type="button"
              className="record-row is-active"
              onClick={() => onSetSelectedConfigIndex(0)}
            >
              Palette 1
            </button>
          </div>
        </aside>

        <section className="record-editor-panel">
          <h2>Palette 1</h2>
          {activeConfigEntries.length === 0 ? <p className="muted">No color entries yet.</p> : null}

          <div className="color-palette-grid5">
            {activeConfigEntries.map((entry, index) => {
              const color = /^#[0-9a-fA-F]{6}$/.test(String(entry.color || "")) ? String(entry.color) : "#000000";
              const symbol = getCatalogEntryIdValue(entry, String(index)).slice(0, 1) || "?";
              return (
                <button
                  key={`cfg-color-cell-${index}-${symbol}`}
                  type="button"
                  className={`color-pixel-btn ${index === selectedConfigIndex ? "is-active" : ""}`}
                  style={{ backgroundColor: color }}
                  title={`${symbol} = ${color}`}
                  onClick={() => onSetSelectedConfigIndex(index)}
                >
                  <span className="color-pixel-label">{symbol}</span>
                </button>
              );
            })}
          </div>

          {selectedColor ? (
            <div className="fields-grid color-palette-editor">
              <div className="field-row">
                <label htmlFor="cfg-id">Symbol</label>
                <input
                  id="cfg-id"
                  value={getCatalogEntryIdValue(selectedColor)}
                  maxLength={1}
                  disabled
                  readOnly
                />
              </div>
              <div className="field-row">
                <label htmlFor="cfg-color">Color</label>
                <input
                  id="cfg-color"
                  type="color"
                  value={/^#[0-9a-fA-F]{6}$/.test(String(selectedColor.color || "")) ? String(selectedColor.color) : "#ffffff"}
                  disabled
                  readOnly
                />
              </div>
              <div className="field-row">
                <label htmlFor="cfg-description">Name</label>
                <input
                  id="cfg-description"
                  value={String(selectedColor.description || "")}
                  disabled
                  readOnly
                />
              </div>
            </div>
          ) : null}
          <p className="muted">Color definitions are locked here because other editors depend on this palette structure.</p>
        </section>
      </div>
    );
  }

  return (
    <div className="structured-layout">
      <aside className="record-list-panel">
        <h2>{activeConfigTab}</h2>
        <div className="record-list">
          {activeConfigEntries.length === 0 ? <p className="muted">No entries yet.</p> : null}
          {activeConfigEntries.map((entry, index) => {
            const key = getCatalogEntryIdValue(entry, String(entry.entryId || `entry-${index + 1}`));
            const label = key || `Entry ${index + 1}`;
            return (
              <button
                key={`cfg-${activeConfigKey}-${key}-${index}`}
                type="button"
                className={`record-row ${index === selectedConfigIndex ? "is-active" : ""}`}
                onClick={() => onSetSelectedConfigIndex(index)}
              >
                {label}
              </button>
            );
          })}
        </div>
      </aside>

      <section className="record-editor-panel">
        <h2>{activeConfigTab} Entry</h2>
        {!selectedConfigEntry ? <p className="muted">Select or add an entry to edit.</p> : null}
        {selectedConfigEntry ? (
          <div className="fields-grid">
            <div className="field-row">
              <label htmlFor="cfg-id">Id</label>
              <input
                id="cfg-id"
                value={getCatalogEntryIdValue(selectedConfigEntry)}
                onChange={(event) => onUpdateActiveConfigEntry(selectedConfigIndex, {
                  key: activeConfigTab === "Colors" ? String(event.target.value || "").slice(0, 1) : event.target.value,
                  sourceKey: activeConfigTab === "Colors" ? String(event.target.value || "").slice(0, 1) : event.target.value,
                  originalName: activeConfigTab === "Colors" ? String(event.target.value || "").slice(0, 1) : event.target.value,
                })}
              />
            </div>
            {activeConfigTab === "Colors" ? (
              <div className="field-row">
                <label htmlFor="cfg-color">Color</label>
                <input
                  id="cfg-color"
                  type="color"
                  value={/^#[0-9a-fA-F]{6}$/.test(String(selectedConfigEntry.color || "")) ? String(selectedConfigEntry.color) : "#ffffff"}
                  onChange={(event) => onUpdateActiveConfigEntry(selectedConfigIndex, { color: event.target.value.toUpperCase() })}
                />
              </div>
            ) : null}
            <div className="field-row">
              <label htmlFor="cfg-description">{activeConfigTab === "Colors" ? "Name" : "Description"}</label>
              <textarea
                id="cfg-description"
                value={String(selectedConfigEntry.description || "")}
                onChange={(event) => onUpdateActiveConfigEntry(selectedConfigIndex, { description: event.target.value })}
              />
            </div>
            {activeConfigTab === "Colors" ? (
              <p className="muted">Colors tab maps a single renderable symbol (Id) to a hex color for sprite/tile palette authoring.</p>
            ) : null}
            <div className="field-row">
              <label htmlFor="cfg-sublist">Sublist Type</label>
              {activeConfigTab === "Colors" ? (
                <input
                  id="cfg-sublist"
                  value=""
                  disabled
                  placeholder="Not used for Colors"
                />
              ) : activeConfigTab === "Conditions" || activeConfigTab === "Item Actions" || activeConfigTab === "System Actions" ? (
                <select
                  id="cfg-sublist"
                  value={String(selectedConfigEntry.sublistType || "")}
                  onChange={(event) => {
                    const nextSublistType = String(event.target.value || "").trim();
                    if (!nextSublistType) {
                      onUpdateActiveConfigEntry(selectedConfigIndex, {
                        sublistType: "",
                        displayKeys: [],
                        passKeys: [],
                      });
                      return;
                    }
                    const nextKeys = getContentFieldKeysByType(nextSublistType);
                    onUpdateActiveConfigEntry(selectedConfigIndex, {
                      sublistType: nextSublistType,
                      displayKeys: nextKeys.includes("name") ? ["name"] : nextKeys.slice(0, 2),
                      passKeys: nextKeys.includes("id") ? ["id"] : nextKeys.slice(0, 1),
                    });
                  }}
                >
                  <option value="">None</option>
                  {rootKeys.map((type) => (
                    <option key={`cfg-sublist-${type}`} value={type}>{typeLabels[type] || type}</option>
                  ))}
                </select>
              ) : (
                <input
                  id="cfg-sublist"
                  value={String(selectedConfigEntry.sublistType || "")}
                  placeholder="items, quests, npcs..."
                  onChange={(event) => onUpdateActiveConfigEntry(selectedConfigIndex, { sublistType: event.target.value })}
                />
              )}
            </div>
            {activeConfigTab === "Colors" ? null : activeConfigTab === "Conditions" || activeConfigTab === "Item Actions" || activeConfigTab === "System Actions" ? (() => {
              const sublistType = String(selectedConfigEntry.sublistType || "").trim();
              const availableKeys = sublistType ? getContentFieldKeysByType(sublistType) : [];
              const selectedDisplayKeys = normalizeStringList(selectedConfigEntry.displayKeys);
              const selectedPassKeys = normalizeStringList(selectedConfigEntry.passKeys);
              return sublistType ? (
                <div className="field-row">
                  <p className="muted">Keys available in {typeLabels[sublistType] || sublistType}: {availableKeys.length > 0 ? availableKeys.join(", ") : "(no records loaded)"}</p>
                  <div className="condition-key-mapping">
                    <div className="condition-key-column">
                      <p className="muted">Display Keys</p>
                      {availableKeys.length > 0 ? availableKeys.map((key) => (
                        <label key={`cfg-display-${sublistType}-${key}`} className="inline-check">
                          <input
                            type="checkbox"
                            checked={selectedDisplayKeys.includes(key)}
                            onChange={(event) => onUpdateActiveConfigEntry(selectedConfigIndex, {
                              displayKeys: event.target.checked
                                ? normalizeStringList([...(selectedConfigEntry.displayKeys || []), key])
                                : normalizeStringList((selectedConfigEntry.displayKeys || []).filter((value) => value !== key)),
                            })}
                          />
                          {key}
                        </label>
                      )) : <p className="muted">No keys available.</p>}
                    </div>
                    <div className="condition-key-column">
                      <p className="muted">Pass Keys</p>
                      {availableKeys.length > 0 ? availableKeys.map((key) => (
                        <label key={`cfg-pass-${sublistType}-${key}`} className="inline-check">
                          <input
                            type="checkbox"
                            checked={selectedPassKeys.includes(key)}
                            onChange={(event) => onUpdateActiveConfigEntry(selectedConfigIndex, {
                              passKeys: event.target.checked
                                ? normalizeStringList([...(selectedConfigEntry.passKeys || []), key])
                                : normalizeStringList((selectedConfigEntry.passKeys || []).filter((value) => value !== key)),
                            })}
                          />
                          {key}
                        </label>
                      )) : <p className="muted">No keys available.</p>}
                    </div>
                  </div>
                </div>
              ) : null;
            })() : (
              <>
                <div className="field-row">
                  <label htmlFor="cfg-display">Display Keys (comma separated)</label>
                  <input
                    id="cfg-display"
                    value={Array.isArray(selectedConfigEntry.displayKeys) ? selectedConfigEntry.displayKeys.join(", ") : ""}
                    onChange={(event) => onUpdateActiveConfigEntry(selectedConfigIndex, { displayKeys: parseCsv(event.target.value) })}
                  />
                </div>
                <div className="field-row">
                  <label htmlFor="cfg-pass">Pass Keys (comma separated)</label>
                  <input
                    id="cfg-pass"
                    value={Array.isArray(selectedConfigEntry.passKeys) ? selectedConfigEntry.passKeys.join(", ") : ""}
                    onChange={(event) => onUpdateActiveConfigEntry(selectedConfigIndex, { passKeys: parseCsv(event.target.value) })}
                  />
                </div>
              </>
            )}
          </div>
        ) : null}
      </section>
    </div>
  );
}
