import React, { useEffect, useState } from "react";
import PropTypes from "prop-types";
import {
  Box,
  Button,
  Checkbox,
  Flex,
  SingleSelect,
  SingleSelectOption,
  TextInput,
  Typography,
} from "@strapi/design-system";
import { getFetchClient } from "@strapi/strapi/admin";

const COLOR_VALUE_PATTERN = /^(#[0-9a-f]{3,8}|rgba?\(|hsla?\()/i;

const COLUMN_OPTIONS = [2, 3, 4, 5, 6, 7, 8, 10];

const ColorsTab = ({ config, onConfigChange }) => {
  const fontColor = config.fontColor ?? { colors: [], columns: 5, colorPicker: true };
  const colors = fontColor.colors ?? [];
  const paletteLayout = fontColor.layout === "list" ? "list" : "grid";
  const [sameForBackground, setSameForBackground] = useState(true);
  const [importSource, setImportSource] = useState("collection");
  const [importUrl, setImportUrl] = useState("");
  const [collectionTypes, setCollectionTypes] = useState([]);
  const [selectedCollection, setSelectedCollection] = useState(null);
  const [importError, setImportError] = useState(null);
  const [importInfo, setImportInfo] = useState(null);

  useEffect(() => {
    const { get } = getFetchClient();
    get("/content-manager/content-types")
      .then(({ data }) => {
        const types = (data?.data ?? data ?? []).filter(
          (type) => type.kind === "collectionType" && type.isDisplayed !== false
        );
        setCollectionTypes(types);
      })
      .catch(() => setCollectionTypes([]));
  }, []);

  const updatePalette = (patch) => {
    const nextFontColor = { ...fontColor, ...patch };
    onConfigChange("fontColor", nextFontColor);

    if (sameForBackground) {
      onConfigChange("fontBackgroundColor", {
        ...(config.fontBackgroundColor ?? {}),
        colors: nextFontColor.colors ?? [],
        columns: nextFontColor.columns,
        colorPicker: nextFontColor.colorPicker,
        layout: nextFontColor.layout,
      });
    }
  };

  const applyColors = (nextColors) => updatePalette({ colors: nextColors });

  const updateColor = (index, patch) =>
    applyColors(colors.map((color, i) => (i === index ? { ...color, ...patch } : color)));

  const addColor = () => applyColors([...colors, { color: "#000000", label: "New color" }]);

  const removeColor = (index) => applyColors(colors.filter((_, i) => i !== index));

  const mergeImported = (imported) => {
    const existing = new Set(colors.map((color) => color.color?.toLowerCase()));
    const fresh = imported.filter((entry) => !existing.has(entry.color?.toLowerCase()));

    if (!fresh.length) {
      setImportInfo("No new colors found (all already in the palette)");
      return;
    }

    applyColors([...colors, ...fresh]);
    setImportInfo(`Imported ${fresh.length} color(s)`);
  };

  const extractColorsFromEntries = (entries) => {
    const imported = [];

    entries.forEach((entry) => {
      if (typeof entry !== "object" || entry === null) return;

      const fields = Object.entries(entry);
      const colorField = fields.find(
        ([, value]) => typeof value === "string" && COLOR_VALUE_PATTERN.test(value.trim())
      );
      if (!colorField) return;

      const labelField = fields.find(
        ([key, value]) =>
          key !== colorField[0] &&
          typeof value === "string" &&
          value.length > 0 &&
          value.length <= 60 &&
          !COLOR_VALUE_PATTERN.test(value.trim()) &&
          !["documentId", "locale", "createdAt", "updatedAt", "publishedAt"].includes(key)
      );

      imported.push({
        color: colorField[1].trim(),
        label: labelField ? labelField[1] : colorField[1].trim(),
      });
    });

    return imported;
  };

  const handleImport = async () => {
    setImportError(null);
    setImportInfo(null);

    try {
      const { get } = getFetchClient();
      let entries;

      if (importSource === "collection") {
        if (!selectedCollection) throw new Error("Choose a collection type first");
        const { data } = await get(
          `/content-manager/collection-types/${selectedCollection}?page=1&pageSize=200`
        );
        entries = data?.results ?? [];
      } else {
        if (!importUrl) throw new Error("Enter a URL first");
        const response = await fetch(importUrl, { credentials: "include" });
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        const payload = await response.json();
        entries = Array.isArray(payload) ? payload : payload?.data ?? payload?.results;
        if (!Array.isArray(entries)) throw new Error("Response is not a list");
      }

      const normalized = entries.map((entry) => ({
        color: entry.color ?? entry.HexCode ?? entry.hex ?? entry.value,
        label: entry.label ?? entry.Text ?? entry.name ?? entry.title,
        ...entry,
      }));

      const imported = extractColorsFromEntries(normalized);
      if (!imported.length) throw new Error("No color values found in the data");

      mergeImported(imported);
    } catch (error) {
      setImportError(`Import failed: ${error.message}`);
    }
  };

  const togglePicker = (checked) => updatePalette({ colorPicker: checked });

  return (
    <Flex direction="column" alignItems="stretch" gap={4}>
      <Flex gap={4} alignItems="flex-end" wrap="wrap">
        <Flex direction="column" alignItems="stretch" gap={1}>
          <Typography variant="pi" fontWeight="bold" textColor="neutral800">
            Palette layout
          </Typography>
          <SingleSelect
            value={paletteLayout}
            onChange={(value) => updatePalette({ layout: value })}
            aria-label="Palette layout"
          >
            <SingleSelectOption value="grid">Grid — compact swatches</SingleSelectOption>
            <SingleSelectOption value="list">List — one per row with names</SingleSelectOption>
          </SingleSelect>
        </Flex>
        {paletteLayout === "grid" && (
          <Flex direction="column" alignItems="stretch" gap={1}>
            <Typography variant="pi" fontWeight="bold" textColor="neutral800">
              Columns
            </Typography>
            <SingleSelect
              value={String(fontColor.columns ?? 5)}
              onChange={(value) => updatePalette({ columns: Number(value) })}
              aria-label="Grid columns"
            >
              {COLUMN_OPTIONS.map((count) => (
                <SingleSelectOption key={count} value={String(count)}>
                  {count}
                </SingleSelectOption>
              ))}
            </SingleSelect>
          </Flex>
        )}
      </Flex>

      <Flex gap={6} alignItems="center" wrap="wrap">
        <Checkbox
          checked={sameForBackground}
          onCheckedChange={(checked) => setSameForBackground(checked === true)}
        >
          Use same palette for background color
        </Checkbox>
        <Checkbox
          checked={fontColor.colorPicker !== false}
          onCheckedChange={(checked) => togglePicker(checked === true)}
        >
          Allow free color picker
        </Checkbox>
      </Flex>

      <Flex direction="column" alignItems="stretch" gap={2}>
        {colors.map((color, index) => (
          <Flex key={index} gap={2} alignItems="center">
            <input
              type="color"
              value={normalizeHex(color.color)}
              onChange={(event) => updateColor(index, { color: event.target.value })}
              style={{ width: 44, height: 34, border: "none", background: "transparent", cursor: "pointer" }}
              aria-label={`Color ${index + 1}`}
            />
            <Box style={{ flex: 1 }}>
              <TextInput
                name={`color-label-${index}`}
                value={color.label ?? ""}
                onChange={(event) => updateColor(index, { label: event.target.value })}
                placeholder="Label"
              />
            </Box>
            <Typography variant="pi" textColor="neutral500">
              {color.color}
            </Typography>
            <Button variant="danger-light" onClick={() => removeColor(index)}>
              Remove
            </Button>
          </Flex>
        ))}
        {colors.length === 0 && (
          <Typography variant="pi" textColor="neutral500">
            No custom colors — the editor will show the CKEditor default palette
          </Typography>
        )}
      </Flex>

      <Flex gap={2}>
        <Button variant="secondary" onClick={addColor}>
          Add color
        </Button>
      </Flex>

      <Box paddingTop={2} padding={4} hasRadius background="neutral100">
        <Typography variant="sigma" textColor="neutral600">
          Import colors
        </Typography>
        <Flex gap={2} paddingTop={2} paddingBottom={2}>
          <Button
            variant={importSource === "collection" ? "default" : "tertiary"}
            onClick={() => setImportSource("collection")}
          >
            From a collection type
          </Button>
          <Button
            variant={importSource === "url" ? "default" : "tertiary"}
            onClick={() => setImportSource("url")}
          >
            From a JSON URL
          </Button>
        </Flex>

        {importSource === "collection" && (
          <Flex gap={2} alignItems="center">
            <Box style={{ flex: 1 }}>
              <SingleSelect
                placeholder="Choose the collection type that stores your colors"
                value={selectedCollection}
                onChange={(value) => setSelectedCollection(value)}
              >
                {collectionTypes.map((type) => (
                  <SingleSelectOption key={type.uid} value={type.uid}>
                    {type.info?.displayName ?? type.uid}
                  </SingleSelectOption>
                ))}
              </SingleSelect>
            </Box>
            <Button variant="secondary" onClick={handleImport} disabled={!selectedCollection}>
              Import
            </Button>
          </Flex>
        )}

        {importSource === "url" && (
          <Flex gap={2} alignItems="center">
            <Box style={{ flex: 1 }}>
              <TextInput
                name="color-import-url"
                value={importUrl}
                onChange={(event) => setImportUrl(event.target.value)}
                placeholder="/radioselect/options or https://example.com/colors.json"
              />
            </Box>
            <Button variant="secondary" onClick={handleImport} disabled={!importUrl}>
              Import
            </Button>
          </Flex>
        )}

        <Box paddingTop={2}>
          <Typography variant="pi" textColor="neutral500">
            Color values are detected automatically (#hex, rgb(), hsl()) together with a label field
          </Typography>
        </Box>
        {importError && (
          <Typography variant="pi" textColor="danger600">
            {importError}
          </Typography>
        )}
        {importInfo && (
          <Typography variant="pi" textColor="success600">
            {importInfo}
          </Typography>
        )}
      </Box>
    </Flex>
  );
};

function normalizeHex(value) {
  if (typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value)) return value;
  if (typeof value === "string" && /^#[0-9a-fA-F]{3}$/.test(value)) {
    return `#${value[1]}${value[1]}${value[2]}${value[2]}${value[3]}${value[3]}`;
  }
  return "#000000";
}

ColorsTab.propTypes = {
  config: PropTypes.object.isRequired,
  onConfigChange: PropTypes.func.isRequired,
};

export default ColorsTab;
