import React, { useState } from "react";
import PropTypes from "prop-types";
import {
  Box,
  Button,
  Flex,
  SingleSelect,
  SingleSelectOption,
  TextInput,
  Typography,
} from "@strapi/design-system";
import {
  missingRequirements,
  normalizeToolbar,
  syncToolbarWithFeatures,
} from "../../registry/features";
import FeaturesTab from "./tabs/FeaturesTab.jsx";
import ToolbarTab from "./tabs/ToolbarTab.jsx";
import ColorsTab from "./tabs/ColorsTab.jsx";
import FontsTab from "./tabs/FontsTab.jsx";
import AdvancedTab from "./tabs/AdvancedTab.jsx";
import PreviewTab from "./tabs/PreviewTab.jsx";

const TABS = [
  { id: "features", label: "Features" },
  { id: "toolbar", label: "Toolbar" },
  { id: "colors", label: "Colors" },
  { id: "fonts", label: "Fonts" },
  { id: "advanced", label: "Advanced (JSON)" },
  { id: "preview", label: "Preview" },
];

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

const PresetEditor = ({ initialDraft, isNew, existingNames, onSave, onCancel }) => {
  const [draft, setDraft] = useState(() => ({
    ...initialDraft,
    toolbar: normalizeToolbar(initialDraft.toolbar ?? []),
  }));
  const [activeTab, setActiveTab] = useState("features");
  const [validationError, setValidationError] = useState(null);

  const updateDraft = (patch) => setDraft((current) => ({ ...current, ...patch }));

  const handleFeaturesChange = (features) =>
    setDraft((current) => ({
      ...current,
      features,
      toolbar: syncToolbarWithFeatures(current.toolbar, current.features, features),
    }));

  const updateConfig = (key, value) =>
    setDraft((current) => ({ ...current, config: { ...current.config, [key]: value } }));

  const dependencyWarnings = missingRequirements(draft.features);

  const handleSave = () => {
    if (!NAME_PATTERN.test(draft.name)) {
      setValidationError("Name must be 1-50 chars: letters, numbers, - or _");
      return;
    }
    if (isNew && existingNames.includes(draft.name)) {
      setValidationError(`Preset "${draft.name}" already exists`);
      return;
    }
    if (dependencyWarnings.length > 0) {
      setValidationError(`Missing dependencies: ${dependencyWarnings.join("; ")}`);
      return;
    }

    setValidationError(null);
    onSave(draft);
  };

  const renderActiveTab = () => {
    if (activeTab === "features") {
      return (
        <FeaturesTab features={draft.features} onChange={handleFeaturesChange} />
      );
    }
    if (activeTab === "toolbar") {
      return (
        <ToolbarTab
          toolbar={draft.toolbar}
          features={draft.features}
          onChange={(toolbar) => updateDraft({ toolbar })}
        />
      );
    }
    if (activeTab === "colors") {
      return <ColorsTab config={draft.config} onConfigChange={updateConfig} />;
    }
    if (activeTab === "fonts") {
      return (
        <FontsTab
          config={draft.config}
          onConfigChange={updateConfig}
          fonts={draft.fonts ?? []}
          onFontsChange={(fonts) => updateDraft({ fonts })}
        />
      );
    }
    if (activeTab === "advanced") {
      return <AdvancedTab config={draft.config} onChange={(config) => updateDraft({ config })} />;
    }
    return <PreviewTab draft={draft} />;
  };

  return (
    <Box background="neutral0" hasRadius shadow="filterShadow" padding={6}>
      <Flex justifyContent="space-between" alignItems="center" paddingBottom={4}>
        <Typography variant="delta" tag="h2">
          {isNew ? "Create preset" : `Edit preset: ${draft.name}`}
        </Typography>
        <Flex gap={2}>
          <Button variant="tertiary" onClick={onCancel}>
            Cancel
          </Button>
          <Button onClick={handleSave}>Save preset</Button>
        </Flex>
      </Flex>

      {validationError && (
        <Box padding={3} marginBottom={4} hasRadius background="danger100">
          <Typography textColor="danger600">{validationError}</Typography>
        </Box>
      )}
      {!validationError && dependencyWarnings.length > 0 && (
        <Box padding={3} marginBottom={4} hasRadius background="warning100">
          <Typography textColor="warning600">
            Missing dependencies: {dependencyWarnings.join("; ")}
          </Typography>
        </Box>
      )}

      <Flex gap={4} paddingBottom={4}>
        <Box style={{ flex: 1 }}>
          <Typography variant="pi" fontWeight="bold" textColor="neutral600">
            Name
          </Typography>
          <TextInput
            name="preset-name"
            value={draft.name}
            disabled={!isNew}
            onChange={(event) => updateDraft({ name: event.target.value })}
            placeholder="myPreset"
          />
        </Box>
        <Box style={{ flex: 2 }}>
          <Typography variant="pi" fontWeight="bold" textColor="neutral600">
            Description
          </Typography>
          <TextInput
            name="preset-description"
            value={draft.description}
            onChange={(event) => updateDraft({ description: event.target.value })}
            placeholder="What is this preset for?"
          />
        </Box>
        <Box style={{ width: 200 }}>
          <Typography variant="pi" fontWeight="bold" textColor="neutral600">
            Editor type
          </Typography>
          <SingleSelect
            value={draft.editorType ?? "classic"}
            onChange={(value) => updateDraft({ editorType: value })}
          >
            <SingleSelectOption value="classic">Classic (top toolbar)</SingleSelectOption>
            <SingleSelectOption value="inline">Inline (toolbar on focus)</SingleSelectOption>
            <SingleSelectOption value="balloon">Balloon (toolbar on select)</SingleSelectOption>
          </SingleSelect>
        </Box>
      </Flex>

      <Flex gap={1} paddingBottom={4} wrap="wrap">
        {TABS.map((tab) => (
          <Button
            key={tab.id}
            variant={activeTab === tab.id ? "default" : "tertiary"}
            onClick={() => setActiveTab(tab.id)}
          >
            {tab.label}
          </Button>
        ))}
      </Flex>

      <Box paddingTop={2}>{renderActiveTab()}</Box>
    </Box>
  );
};

PresetEditor.propTypes = {
  initialDraft: PropTypes.object.isRequired,
  isNew: PropTypes.bool.isRequired,
  existingNames: PropTypes.array.isRequired,
  onSave: PropTypes.func.isRequired,
  onCancel: PropTypes.func.isRequired,
};

export default PresetEditor;
