import { Box, ColorPicker, Group, Modal, Text, Tooltip } from "@mantine/core";
import { IconPalette } from "@tabler/icons-react";
import { useState, type FC } from "react";
import { colorBorder } from "./color_border";
import { colorSwatch } from "./color_swatch";

/** Paleta de 27 opciones por defecto: tokens Mantine + hexadecimales de acento. */
export const DEFAULT_COLOR_OPTIONS: { value: string; label: string }[] = [
  { value: "", label: "Default" },
  { value: "blue", label: "Azul" },
  { value: "cyan", label: "Cian" },
  { value: "teal", label: "Teal" },
  { value: "green", label: "Verde" },
  { value: "lime", label: "Lima" },
  { value: "yellow", label: "Amarillo" },
  { value: "orange", label: "Naranja" },
  { value: "red", label: "Rojo" },
  { value: "pink", label: "Rosa" },
  { value: "grape", label: "Uva" },
  { value: "violet", label: "Violeta" },
  { value: "indigo", label: "Indigo" },
  { value: "gray", label: "Gris" },
  { value: "#0ea5e9", label: "Sky" },
  { value: "#14b8a6", label: "Esmeralda" },
  { value: "#84cc16", label: "Lima fluor" },
  { value: "#ec4899", label: "Magenta" },
  { value: "#a855f7", label: "Lavanda" },
  { value: "#f97316", label: "Mandarina" },
  { value: "#dc2626", label: "Rubi" },
  { value: "#0891b2", label: "Petroleo" },
  { value: "#fde047", label: "Limon" },
  { value: "#10b981", label: "Menta" },
  { value: "#fb7185", label: "Coral" },
  { value: "#6366f1", label: "Iris" },
  { value: "#94a3b8", label: "Pizarra" },
];

const DEFAULT_CUSTOM_SWATCHES = [
  "#1c7ed6", "#15aabf", "#12b886", "#37b24d", "#82c91e",
  "#fab005", "#fd7e14", "#fa5252", "#e64980", "#be4bdb",
  "#7950f2", "#4c6ef5", "#868e96", "#212529",
];

export interface ColorPickerGridProps {
  /** Color seleccionado actualmente (token Mantine o hex). */
  value: string;
  /** Callback invocado al seleccionar cualquier color, incluido el picker libre. */
  onChange: (color: string) => void;
  /** Lista de opciones a mostrar como swatches. Default: DEFAULT_COLOR_OPTIONS. */
  options?: { value: string; label: string }[];
  /** Diametro de cada swatch en px. Default: 26. */
  swatchSize?: number;
  /** Swatches rapidos dentro del ColorPicker de Mantine. Default: 14 hexadecimales. */
  customSwatches?: string[];
  /** Titulo del modal del picker libre. Default: "Color personalizado". */
  modalTitle?: string;
}

/**
 * Grid de swatches de color con boton "+" que abre un ColorPicker de Mantine
 * para seleccionar un hexadecimal personalizado via modal.
 */
export const ColorPickerGrid: FC<ColorPickerGridProps> = ({
  value,
  onChange,
  options = DEFAULT_COLOR_OPTIONS,
  swatchSize = 26,
  customSwatches = DEFAULT_CUSTOM_SWATCHES,
  modalTitle = "Color personalizado",
}) => {
  const [pickerOpen, setPickerOpen] = useState(false);
  const [custom, setCustom] = useState(
    value && value.startsWith("#") ? value : "#888888"
  );

  const isCustomActive =
    !!value && value.startsWith("#") && !options.some((o) => o.value === value);

  return (
    <>
      <Group gap={6} maw={280}>
        {options.map((c) => {
          const selected = value === c.value;
          return (
            <Tooltip key={c.value || "default"} label={c.label} withArrow>
              <Box
                role="button"
                onClick={(e) => {
                  e.stopPropagation();
                  onChange(c.value);
                }}
                aria-label={c.label}
                style={{
                  width: swatchSize,
                  height: swatchSize,
                  borderRadius: "50%",
                  background: colorSwatch(c.value),
                  border: `2px solid ${selected ? "var(--mantine-color-white)" : colorBorder(c.value)}`,
                  boxShadow: selected
                    ? "0 0 0 2px var(--mantine-color-blue-5)"
                    : undefined,
                  cursor: "pointer",
                  flexShrink: 0,
                  transition: "transform .1s",
                }}
              />
            </Tooltip>
          );
        })}

        <Tooltip label="Color personalizado" withArrow>
          <Box
            role="button"
            onClick={(e) => {
              e.stopPropagation();
              setPickerOpen(true);
            }}
            aria-label="Color personalizado"
            style={{
              width: swatchSize,
              height: swatchSize,
              borderRadius: "50%",
              background: isCustomActive ? custom : "transparent",
              border: `2px dashed ${isCustomActive ? custom : "var(--mantine-color-gray-5)"}`,
              boxShadow: isCustomActive
                ? "0 0 0 2px var(--mantine-color-blue-5)"
                : undefined,
              cursor: "pointer",
              flexShrink: 0,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              color: "var(--mantine-color-gray-3)",
            }}
          >
            <IconPalette size={14} />
          </Box>
        </Tooltip>
      </Group>

      <Modal
        opened={pickerOpen}
        onClose={() => setPickerOpen(false)}
        title={modalTitle}
        size="auto"
        centered
        withinPortal
        zIndex={2000}
        closeOnClickOutside={false}
        closeOnEscape={false}
        trapFocus={false}
      >
        <ColorPicker
          value={custom}
          onChange={(v) => {
            setCustom(v);
            onChange(v);
          }}
          format="hex"
          swatches={customSwatches}
          fullWidth
        />
        <Text size="xs" c="dimmed" mt="sm">
          {custom.toUpperCase()}
        </Text>
      </Modal>
    </>
  );
};
