import { useFields } from "@/hooks/useFields";
import { __, sprintf } from "@wordpress/i18n";
import { useState } from "react";
import { useDragSort } from "../lib/useDragSort";
import FieldRow from "./FieldRow";

const listClass =
  "ino:m-0 ino:flex ino:list-none ino:flex-col ino:gap-1.5 ino:p-0";
const headingClass =
  "ino:mt-4 ino:mb-2 ino:text-xs ino:font-semibold ino:tracking-wide ino:text-muted-foreground ino:uppercase";

/**
 * The rows: the product header (image, name, Add to cart: on/off only, it
 * always sits on top) and the spec rows, which can be dragged with the
 * mouse or touch, or moved with Arrow Up / Down. Moves are announced.
 */
const FieldList = () => {
  const { header, spec, reorder, toggle, remove } = useFields();
  const [announce, setAnnounce] = useState("");

  const moveTo = (from, to, handle) => {
    if (to < 0 || to >= spec.length) {
      return;
    }
    const field = spec[from];
    reorder(from, to);
    setAnnounce(
      sprintf(
        /* translators: 1: row name, 2: new position */
        __(
          "%1$s moved to position %2$d.",
          "product-comparison-for-woocommerce",
        ),
        field.label || field.default_label || field.key,
        to + 1,
      ),
    );
    if (handle) {
      // Keep keyboard focus on the moved row's handle.
      requestAnimationFrame(() =>
        handle.closest("ul")?.children[to]?.querySelector("button")?.focus(),
      );
    }
  };

  const { drag, handleProps, indicator } = useDragSort((from, to) =>
    moveTo(from, to),
  );

  return (
    <>
      <p className={headingClass} style={{ marginTop: 0 }}>
        {__("Product header", "product-comparison-for-woocommerce")}
      </p>
      <ul className={listClass}>
        {header.map((field, index) => (
          <FieldRow
            key={field.key}
            field={field}
            index={index}
            total={header.length}
            onToggle={toggle}
          />
        ))}
      </ul>
      <p className={headingClass}>
        {__("Rows, in table order", "product-comparison-for-woocommerce")}
      </p>
      <ul className={listClass}>
        {spec.map((field, index) => (
          <FieldRow
            key={field.key}
            field={field}
            index={index}
            total={spec.length}
            handle={handleProps(index)}
            dragging={drag?.from === index}
            line={indicator(index)}
            onKeyMove={moveTo}
            onToggle={toggle}
            onRemove={field.type === "meta" ? remove : undefined}
          />
        ))}
      </ul>
      <p className="ino:sr-only" aria-live="polite">
        {announce}
      </p>
    </>
  );
};

export default FieldList;
