import styled from '@emotion/styled';
import parse from 'parse-css-color';

import { FALLBACK_IMAGE_URL } from '@/utils/constants';

import Button, { ButtonShape, ButtonVariant } from '../button/Button';
import { ContextMenuTrigger } from '../contextMenu/ContextMenu';

const Grid = styled.div`
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 2px;
  background-color: var(--color-background-secondary);
  padding: 4px;
`;

export const colorOptions = [
  'rgb(112, 25, 67)',
  'rgb(152, 30, 89)',
  'rgb(222, 22, 119)',
  'rgb(253, 66, 156)',
  'rgb(255, 120, 185)',

  'rgb(0, 74, 152)',
  'rgb(0, 92, 190)',
  'rgb(0, 113, 234)',
  'rgb(31, 139, 255)',
  'rgb(88, 168, 255)',

  'rgb(141, 59, 0)',
  'rgb(188, 78, 0)',
  'rgb(255, 106, 0)',
  'rgb(255, 148, 72)',
  'rgb(255, 178, 123)',

  'rgb(1, 116, 49)',
  'rgb(1, 144, 61)',
  'rgb(2, 175, 74)',
  'rgb(2, 217, 92)',
  'rgb(35, 253, 126)',

  'rgb(114, 95, 3)',
  'rgb(148, 125, 4)',
  'rgb(180, 156, 5)',
  'rgb(212, 187, 6)',
  'rgb(245, 217, 7)',

  'rgb(77, 51, 183)',
  'rgb(98, 68, 215)',
  'rgb(114, 81, 247)',
  'rgb(139, 110, 254)',
  'rgb(158, 134, 255)',

  'rgb(144, 30, 4)',
  'rgb(195, 41, 6)',
  'rgb(248, 68, 27)',
  'rgb(250, 118, 88)',
  'rgb(251, 155, 133)',

  'rgb(49, 114, 3)',
  'rgb(61, 141, 3)',
  'rgb(74, 171, 4)',
  'rgb(91, 210, 5)',
  'rgb(122, 250, 31)',
].map(
  (color) =>
    '#' +
    parse(color)
      ?.values.map((c) => c.toString(16).padStart(2, '0'))
      .join('')
);

export default function ColorPicker({
  color,
  setColor,
}: {
  color: string | null;
  setColor: (color: string) => void;
}) {
  return (
    <ContextMenuTrigger
      placement='bottom-right'
      ButtonComponent={(props) => (
        <Button
          {...props}
          shape={ButtonShape.Pill}
          className='p-1.5'
          variant={ButtonVariant.LightGlass}
          icon={
            <div
              className='h-6 w-6 rounded-full'
              style={
                color
                  ? { backgroundColor: color }
                  : {
                      backgroundImage: `url(${FALLBACK_IMAGE_URL})`,
                      backgroundSize: '45px 45px',
                    }
              }
            />
          }
        />
      )}
      ContentsComponent={() => (
        <>
          <Grid>
            {colorOptions.map((option) => (
              <Button
                key={option}
                onClick={() => setColor(option)}
                shape={ButtonShape.Pill}
                className={`p-0.5 ${option === color ? 'bg-white' : 'bg-[rgba(0,0,0,0.2)]'} hover:bg-white/50`}
                icon={
                  <div
                    className='h-8 w-8 rounded-full'
                    style={{ backgroundColor: option }}
                  />
                }
              />
            ))}
          </Grid>
        </>
      )}
    />
  );
}
