import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useFields } from "@/hooks/useFields";
import { __, sprintf } from "@wordpress/i18n";
import { useState } from "react";

const VALID = /^[A-Za-z0-9_-]{1,190}$/;

/** "energy_class" → "Energy class". */
const labelFor = (key) => {
  const text = key.replace(/[_-]+/g, " ").trim();
  return text.charAt(0).toUpperCase() + text.slice(1);
};

/**
 * Table rows › "Add a custom field" (Pro): adds a `meta:<key>` row from a
 * product custom field key. ACF, Meta Box, taxonomy and custom attribute
 * rows show up in the list on their own.
 */
const AddCustomField = () => {
  const { add, fields } = useFields();
  const [key, setKey] = useState("");
  const [error, setError] = useState("");
  const id = "pcfw-custom-field-key";

  const submit = (event) => {
    event.preventDefault();
    const value = key.trim();

    if (!VALID.test(value)) {
      setError(
        __(
          "Use letters, numbers, _ or - only.",
          "product-comparison-for-woocommerce",
        ),
      );
      return;
    }

    if (fields.some((f) => f.key === `meta:${value}`)) {
      setError(
        sprintf(
          /* translators: %s: custom field key */
          __("%s is already a row.", "product-comparison-for-woocommerce"),
          value,
        ),
      );
      return;
    }

    add({
      key: `meta:${value}`,
      type: "meta",
      label: "",
      enabled: true,
      default_label: labelFor(value),
      pro: true,
    });
    setKey("");
    setError("");
  };

  return (
    <form
      onSubmit={submit}
      className="ino:flex ino:flex-col ino:gap-2 ino:border-t ino:border-border/70 ino:pt-3"
    >
      <label htmlFor={id} className="ino:text-[13px] ino:font-medium">
        {__("Add a custom field", "product-comparison-for-woocommerce")}
      </label>
      <div className="ino:flex ino:flex-wrap ino:gap-2">
        <Input
          id={id}
          value={key}
          placeholder="energy_class"
          aria-invalid={error ? "true" : undefined}
          aria-describedby={`${id}-help`}
          onChange={(event) => setKey(event.target.value)}
          className="ino:w-64 ino:font-mono ino:text-[13px]"
        />
        <Button type="submit" variant="outline">
          {__("+ Add row", "product-comparison-for-woocommerce")}
        </Button>
      </div>
      <p
        id={`${id}-help`}
        className="ino:m-0 ino:text-xs ino:text-muted-foreground"
        role={error ? "alert" : undefined}
      >
        {error ||
          __(
            "The product's custom field (meta) key. ACF, Meta Box, taxonomy and custom attribute rows appear in the list above on their own.",
            "product-comparison-for-woocommerce",
          )}
      </p>
    </form>
  );
};

export default AddCustomField;
