import React from 'react';
import { cn, withRef } from '@udecode/cn';
import { PlateElement, useElement } from '@udecode/plate-common';
import { cva } from 'class-variance-authority';
import { CalendarDays } from 'lucide-react';

import { TStatusElement } from '../status-store';
import { StatusToolbarPopover } from './status-toolbar-popover';

export const StatusComponent = withRef<typeof PlateElement>(
  ({ className, children, ...props }, ref) => {
    const { category, value } = useElement<TStatusElement>();

    const Status = cva(
      [
        'font-semibold',
        'rounded',
        'border-transparent',
        'px-2',
        'py-0.5',
        'mx-1',
      ],
      {
        variants: {
          category: {
            gray: ['bg-slate-500', 'text-white', 'hover:bg-slate-600'],
            red: ['bg-red-500', 'text-white', 'hover:bg-red-600'],
            yellow: ['bg-amber-500', 'text-black', 'hover:bg-amber-600'],
            green: ['bg-green-700', 'text-white', 'hover:bg-green-800'],
            blue: ['bg-blue-700', 'text-white', 'hover:bg-blue-800'],
            time: ['bg-slate-300', 'text-black', 'hover:bg-slate-200'],
          },
        },
        compoundVariants: [
          {
            category: 'gray',
          },
        ],
        defaultVariants: {
          category: 'gray',
        },
      }
    );

    return (
      <StatusToolbarPopover>
        <PlateElement
          ref={ref}
          asChild
          contentEditable={false}
          data-slate-value={value}
          className={cn(className)}
          {...props}
        >
          <div className={cn('cursor-pointer', Status({ category: category }))}>
            {category === 'time' && (
              <CalendarDays width={15} className="-mt-1 mr-1 inline" />
            )}
            {value}
            {children}
          </div>
        </PlateElement>
      </StatusToolbarPopover>
    );
  }
);
