import Segmented from "@/components/settings/Segmented";
import { Button } from "@/components/ui/button";
import { useTemplateLoader } from "@/hooks/useTemplateLoader";
import { useAppDispatch, useAppSelector } from "@/store";
import {
  useDeleteTemplateMutation,
  useGetTemplateCategoriesQuery,
} from "@/store/api/templatesApi";
import {
  scopeChanged,
  selectScope,
  selectTemplateDraft,
  selectTemplateIsDirty,
} from "@/store/slices/templateSlice";
import { __, sprintf } from "@wordpress/i18n";

const NOTE = "ino:mt-2 ino:mb-0 ino:text-xs ino:text-muted-foreground";

/**
 * Table fields › "Rows for" (Pro): edit the global rows, or a product
 * category's own rows and groups (a template). The row list, its options
 * and the Spec groups card below follow the choice.
 */
const RowsFor = () => {
  const dispatch = useAppDispatch();
  const termId = useAppSelector(selectScope);
  const template = useAppSelector(selectTemplateDraft);
  const dirty = useAppSelector(selectTemplateIsDirty);
  const categories = useGetTemplateCategoriesQuery().data ?? [];
  const templates = useTemplateLoader(categories);
  const [remove, removing] = useDeleteTemplateMutation();
  const pick = (value) => !dirty && dispatch(scopeChanged(value));
  const own = (id) => templates.some((t) => t.term_ids.includes(id));
  const name = template && termId ? template.name : "";

  return (
    <div className="ino:mb-4 ino:rounded-lg ino:bg-muted/60 ino:p-3">
      <Segmented
        label={__("Rows for", "product-comparison-for-woocommerce")}
        value={termId ? "category" : "all"}
        disabled={dirty}
        onChange={(v) =>
          pick(v === "all" ? null : (categories[0] && categories[0].id) || null)
        }
        options={[
          {
            value: "all",
            label: __("All products", "product-comparison-for-woocommerce"),
          },
          {
            value: "category",
            label: __("A category…", "product-comparison-for-woocommerce"),
          },
        ]}
      />
      {termId && (
        <select
          aria-label={__("Category", "product-comparison-for-woocommerce")}
          value={termId}
          disabled={dirty}
          onChange={(event) => pick(Number(event.target.value))}
          className="ino:mt-2 ino:h-9 ino:w-full ino:rounded-md ino:border ino:border-input ino:bg-background ino:px-2 ino:text-sm"
        >
          {categories.map((c) => (
            <option key={c.id} value={c.id}>
              {own(c.id) ? `${c.name} ✓` : c.name}
            </option>
          ))}
        </select>
      )}
      {dirty && (
        <p className={NOTE}>
          {__(
            "Save or discard your changes to switch.",
            "product-comparison-for-woocommerce",
          )}
        </p>
      )}
      {termId && template && !template.id && (
        <p className={NOTE}>
          {sprintf(
            /* translators: %s: category name */
            __(
              "%s uses the global rows. Change anything below and Save to give it its own rows.",
              "product-comparison-for-woocommerce",
            ),
            name,
          )}
        </p>
      )}
      {termId && template && template.id && (
        <div className="ino:mt-2 ino:flex ino:flex-wrap ino:items-center ino:justify-between ino:gap-2">
          <p className={NOTE.replace("ino:mt-2 ", "")}>
            {sprintf(
              /* translators: %s: category name */
              __(
                "%s has its own rows and groups.",
                "product-comparison-for-woocommerce",
              ),
              name,
            )}
          </p>
          <Button
            variant="outline"
            size="sm"
            disabled={removing.isLoading}
            onClick={() =>
              remove(template.id)
                .unwrap()
                .then(() => dispatch(scopeChanged(null)))
            }
          >
            {__("Use the global rows", "product-comparison-for-woocommerce")}
          </Button>
        </div>
      )}
      {!termId && (
        <p className={NOTE}>
          {__(
            "Categories marked ✓ have their own rows; the rest use these.",
            "product-comparison-for-woocommerce",
          )}
        </p>
      )}
    </div>
  );
};

export default RowsFor;
