import { ColorPicker, TextInput, Stack, Group, ColorSwatch, Text } from '@mantine/core';
import React, { useState, useCallback, useMemo } from 'react';
import { useLingui } from '@lingui/react/macro';

const presetColors = [
  '#FF0000', '#00FF00', '#0000FF', '#FFFF00', 
  '#FF00FF', '#00FFFF', '#FFA500', '#800080',
  '#008000', '#000080', '#800000', '#808000'
];

interface TeamColorPickerProps {
  value: string;
  onChange: (value: string) => void;
  label?: string;
}

const TeamColorPicker: React.FC<TeamColorPickerProps> = ({
  value,
  onChange,
  label
}) => {
  const { t } = useLingui();
  const displayLabel = label ?? t`Select Color`;
  const [customHex, setCustomHex] = useState(value || '');

  const isValidHex = useMemo(() => {
    const hexRegex = /^#[0-9A-F]{6}$/i;
    return hexRegex.test(customHex);
  }, [customHex]);

  const handleColorChange = useCallback((color: string) => {
    setCustomHex(color);
    onChange(color);
  }, [onChange]);

  const handleHexInputChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    const hex = event.currentTarget.value;
    setCustomHex(hex);
    
    if (/^#[0-9A-F]{6}$/i.test(hex)) {
      onChange(hex);
    }
  }, [onChange]);

  return (
      <Stack gap="md" p="md" w="100%">
        <Text fw={500}>{displayLabel}</Text>
        
        <ColorPicker
          value={value || '#000000'}
          onChange={handleColorChange}
          format="hex"
          swatches={presetColors}
          withPicker={true}
          fullWidth
          size="md"
          swatchesPerRow={12}
        />

        <Group gap="xs" align="flex-end">
          <TextInput
            style={{ flex: 1 }}
            label={t`Custom Hex Code`}
            placeholder="#FF0000"
            value={customHex}
            onChange={handleHexInputChange}
            error={customHex && !isValidHex ? t`Invalid hex color format` : undefined}
            w="100%"
          />
          
          {isValidHex && (
            <ColorSwatch
              color={customHex}
              size={36}
              style={{ marginBottom: customHex && !isValidHex ? 24 : 0 }}
            />
          )}
        </Group>
      </Stack>
  );
};

export default TeamColorPicker;