import React from "react";
import PropTypes from "prop-types";
import { Box, Button, Flex, Typography } from "@strapi/design-system";
import {
  FEATURE_GROUPS,
  FEATURE_REGISTRY,
  featureIconMarkup,
  toolbarItemMeta,
} from "../../../registry/features";

const ITEM_LABELS = {
  undo: "Undo",
  redo: "Redo",
  heading: "Headings dropdown",
  fontFamily: "Font family",
  fontSize: "Font size",
  fontWeight: "Font weight",
  blockSpacing: "Block spacing (padding)",
  fontColor: "Text color",
  fontBackgroundColor: "Text background color",
  bold: "Bold",
  italic: "Italic",
  underline: "Underline",
  strikethrough: "Strikethrough",
  code: "Inline code",
  subscript: "Subscript",
  superscript: "Superscript",
  removeFormat: "Clear formatting",
  highlight: "Highlight",
  alignment: "Text alignment",
  bulletedList: "Bulleted list",
  numberedList: "Numbered list",
  todoList: "To-do list",
  outdent: "Decrease indent",
  indent: "Increase indent",
  blockQuote: "Block quote",
  horizontalLine: "Horizontal line",
  pageBreak: "Page break",
  codeBlock: "Code block",
  link: "Insert link",
  bookmark: "Bookmark",
  uploadImage: "Upload image",
  insertImage: "Insert image",
  mediaEmbed: "Embed media (YouTube…)",
  strapiMediaLib: "Strapi media library",
  insertTable: "Insert table",
  specialCharacters: "Special characters",
  emoji: "Emoji",
  findAndReplace: "Find & replace",
  sourceEditing: "Source (HTML)",
  showBlocks: "Show blocks",
  htmlEmbed: "HTML embed",
  style: "Styles dropdown",
  fullscreen: "Fullscreen",
  ckstudioAI: "AI assistant",
};

const labelFor = (item) => ITEM_LABELS[item] ?? item;

const itemIconStyle = {
  display: "inline-flex",
  alignItems: "center",
  justifyContent: "center",
  width: 16,
  height: 16,
  flex: "0 0 auto",
  opacity: 0.8,
};

const ItemIcon = ({ item }) => {
  const markup = featureIconMarkup(toolbarItemMeta(item).icon);
  if (!markup) return null;
  return <span style={itemIconStyle} aria-hidden="true" dangerouslySetInnerHTML={{ __html: markup }} />;
};

ItemIcon.propTypes = { item: PropTypes.string.isRequired };

const ToolbarTab = ({ toolbar, features, onChange }) => {
  const moveItem = (index, direction) => {
    const target = index + direction;
    if (target < 0 || target >= toolbar.length) return;

    const next = [...toolbar];
    [next[index], next[target]] = [next[target], next[index]];
    onChange(next);
  };

  const removeItem = (index) => onChange(toolbar.filter((_, i) => i !== index));
  const addItem = (item) => onChange([...toolbar, item]);

  const renderPreview = () => (
    <Box padding={3} hasRadius background="neutral100">
      <Typography variant="sigma" textColor="neutral600">
        1. Toolbar preview — this is the order editors will see
      </Typography>
      <Flex wrap="wrap" gap={1} paddingTop={2} alignItems="center">
        {toolbar.length === 0 && (
          <Typography variant="pi" textColor="neutral500">
            Toolbar is empty — add buttons from the list below
          </Typography>
        )}
        {toolbar.map((item, index) =>
          item === "|" ? (
            <Box
              key={`sep-${index}`}
              style={{ width: 1, height: 22, background: "currentColor", opacity: 0.35, margin: "0 4px" }}
            />
          ) : (
            <Flex
              key={`${item}-${index}`}
              gap={1}
              alignItems="center"
              paddingLeft={2}
              paddingRight={2}
              paddingTop={1}
              paddingBottom={1}
              hasRadius
              background="neutral0"
              title={toolbarItemMeta(item).description}
            >
              <ItemIcon item={item} />
              <Typography variant="pi">{labelFor(item)}</Typography>
            </Flex>
          )
        )}
      </Flex>
    </Box>
  );

  const renderAvailable = () => (
    <Box style={{ flex: 1, minWidth: 320 }}>
      <Typography variant="sigma" textColor="neutral600">
        2. Available buttons — click "+" to add
      </Typography>
      <Typography variant="pi" textColor="neutral500">
        The list depends on the features enabled in the Features tab
      </Typography>
      <Flex direction="column" alignItems="stretch" gap={3} paddingTop={2}>
        {FEATURE_GROUPS.map((group) => {
          const groupItems = features
            .filter((name) => FEATURE_REGISTRY[name]?.group === group.id)
            .flatMap((name) => FEATURE_REGISTRY[name]?.toolbar ?? []);
          const uniqueItems = [...new Set(groupItems)];

          if (!uniqueItems.length) return null;

          return (
            <Box key={group.id}>
              <Typography variant="pi" fontWeight="bold" textColor="neutral600">
                {group.label}
              </Typography>
              <Flex wrap="wrap" gap={2} paddingTop={1}>
                {uniqueItems.map((item) => {
                  const alreadyAdded = toolbar.includes(item);

                  return (
                    <Flex
                      key={item}
                      gap={1}
                      alignItems="center"
                      paddingLeft={2}
                      paddingRight={1}
                      paddingTop={1}
                      paddingBottom={1}
                      hasRadius
                      background={alreadyAdded ? "neutral150" : "neutral100"}
                      style={{ opacity: alreadyAdded ? 0.55 : 1 }}
                      title={toolbarItemMeta(item).description}
                    >
                      <ItemIcon item={item} />
                      <Typography variant="pi">{labelFor(item)}</Typography>
                      <button
                        type="button"
                        onClick={() => addItem(item)}
                        disabled={alreadyAdded}
                        style={{ ...chipButtonStyle, fontWeight: "bold", fontSize: 14 }}
                        title={alreadyAdded ? "Already in the toolbar" : `Add ${labelFor(item)}`}
                        aria-label={`Add ${labelFor(item)}`}
                      >
                        {alreadyAdded ? "✓" : "+"}
                      </button>
                    </Flex>
                  );
                })}
              </Flex>
            </Box>
          );
        })}
      </Flex>
    </Box>
  );

  const renderCurrent = () => (
    <Box style={{ flex: 1, minWidth: 320 }}>
      <Flex justifyContent="space-between" alignItems="center">
        <Typography variant="sigma" textColor="neutral600">
          3. Current toolbar — reorder with ↑ ↓
        </Typography>
        <Button variant="tertiary" onClick={() => addItem("|")}>
          + Add separator line
        </Button>
      </Flex>
      <Flex direction="column" alignItems="stretch" gap={1} paddingTop={2}>
        {toolbar.map((item, index) => (
          <Flex
            key={`${item}-${index}`}
            gap={2}
            alignItems="center"
            padding={2}
            hasRadius
            background={item === "|" ? "neutral150" : "neutral100"}
          >
            <Typography variant="pi" textColor="neutral500" style={{ width: 24, textAlign: "right" }}>
              {index + 1}.
            </Typography>
            {item !== "|" && <ItemIcon item={item} />}
            <Box style={{ flex: 1 }} title={item === "|" ? undefined : toolbarItemMeta(item).description}>
              <Typography variant="pi" fontWeight={item === "|" ? "bold" : undefined}>
                {item === "|" ? "── separator ──" : labelFor(item)}
              </Typography>
            </Box>
            <button
              type="button"
              onClick={() => moveItem(index, -1)}
              disabled={index === 0}
              style={chipButtonStyle}
              title="Move up"
              aria-label={`Move ${labelFor(item)} up`}
            >
              ↑
            </button>
            <button
              type="button"
              onClick={() => moveItem(index, 1)}
              disabled={index === toolbar.length - 1}
              style={chipButtonStyle}
              title="Move down"
              aria-label={`Move ${labelFor(item)} down`}
            >
              ↓
            </button>
            <button
              type="button"
              onClick={() => removeItem(index)}
              style={{ ...chipButtonStyle, color: "#ee5e52" }}
              title="Remove from toolbar"
              aria-label={`Remove ${labelFor(item)}`}
            >
              ✕
            </button>
          </Flex>
        ))}
        {toolbar.length === 0 && (
          <Typography variant="pi" textColor="neutral500">
            Nothing here yet
          </Typography>
        )}
      </Flex>
    </Box>
  );

  return (
    <Flex direction="column" alignItems="stretch" gap={4}>
      {renderPreview()}
      <Flex gap={6} alignItems="flex-start" wrap="wrap">
        {renderAvailable()}
        {renderCurrent()}
      </Flex>
    </Flex>
  );
};

const chipButtonStyle = {
  border: "none",
  background: "transparent",
  cursor: "pointer",
  padding: "2px 5px",
  color: "inherit",
};

ToolbarTab.propTypes = {
  toolbar: PropTypes.array.isRequired,
  features: PropTypes.array.isRequired,
  onChange: PropTypes.func.isRequired,
};

export default ToolbarTab;
