import { Button, Input } from "@fluentui/react-components";
import { Add24Regular, Delete24Regular } from "@fluentui/react-icons";
import { useMemo, useRef } from "react";
import {
  createStableStringEntry,
  reconcileStableStringEntries,
  StableStringEntry,
} from "./stableListEntries";

interface StringListEditorProps {
  items: string[];
  onChange: (next: string[]) => void;
  placeholder?: string;
  addLabel?: string;
}

export function StringListEditor({
  items,
  onChange,
  placeholder,
  addLabel = "Add entry",
}: StringListEditorProps): React.JSX.Element {
  const entriesRef = useRef<StableStringEntry[]>(
    items.map(createStableStringEntry),
  );

  const entries = useMemo(() => {
    if (
      entriesRef.current.length === items.length &&
      entriesRef.current.every((entry, index) => entry.value === items[index])
    ) {
      return entriesRef.current;
    }

    const reconciled = reconcileStableStringEntries(entriesRef.current, items);
    entriesRef.current = reconciled;
    return reconciled;
  }, [items]);

  const handleChange = (index: number, value: string): void => {
    const next = [...items];
    next[index] = value;
    onChange(next);
  };

  const handleDelete = (index: number): void => {
    onChange(items.filter((_, i) => i !== index));
  };

  const handleAdd = (): void => {
    onChange([...items, ""]);
  };

  return (
    <div>
      {entries.map(({ id, value }, index) => (
        <div key={id} style={{ display: "flex", gap: 4, marginBottom: 4, alignItems: "center" }}>
          <Input
            value={value}
            size="small"
            style={{ flex: 1, fontFamily: "monospace" }}
            placeholder={placeholder}
            aria-label={`Entry ${String(index + 1)}${value ? `: ${value}` : ""}`}
            onChange={(_e, d) => { handleChange(index, d.value); }}
          />
          <Button
            icon={<Delete24Regular />}
            size="small"
            appearance="subtle"
            onClick={() => { handleDelete(index); }}
            aria-label="Remove entry"
          />
        </div>
      ))}
      <Button
        icon={<Add24Regular />}
        size="small"
        appearance="outline"
        onClick={handleAdd}
        style={{ marginTop: 4 }}
      >
        {addLabel}
      </Button>
    </div>
  );
}
