import React, { useRef } from 'react';
import { cn } from '@udecode/cn';
import {
  isSelectionExpanded,
  useEditorSelector,
  useRemoveNodeButton,
} from '@udecode/plate-common';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { useReadOnly, useSelected } from 'slate-react';

import { Calendar } from '@/components/ui/calendar';
import { Icons, iconVariants } from '@/components/icons';
import { IfElse } from '@/components/if-else';
import { Button } from '@/components/plate-ui/button';
import { inputVariants } from '@/components/plate-ui/input';
import {
  Popover,
  PopoverAnchor,
  PopoverContent,
} from '@/components/plate-ui/popover';
import { Separator } from '@/components/plate-ui/separator';

import { useStatusState } from '../status-store';
import { ColorDropdownMenu } from './color-dropdown-menu';

function StatusCalendar() {
  const { element, setStatusValue } = useStatusState();

  const { value } = element;

  return (
    <Calendar
      mode="single"
      selected={new Date(value || '')}
      onSelect={(date) => {
        if (!date) return;
        setStatusValue({
          value: format(date!, 'yyyy-MM-dd', { locale: zhCN }),
        });
      }}
    />
  );
}

export interface StatusToolbarPopoverProps {}

export function StatusToolbarPopover({
  children,
}: React.PropsWithChildren<StatusToolbarPopoverProps>) {
  const readOnly = useReadOnly();
  const selected = useSelected();
  const inputRef = useRef<HTMLInputElement>(null);

  const { element, setStatusValue } = useStatusState();

  const { value, category } = element;

  const { props: buttonProps } = useRemoveNodeButton({ element });

  const selectionCollapsed = useEditorSelector(
    (editor) => !isSelectionExpanded(editor),
    []
  );
  const isOpen = !readOnly && selected && selectionCollapsed;

  const onInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      setStatusValue({ value: inputRef.current?.value });
    }
  };

  if (readOnly) return <div className="inline-block">{children}</div>;

  return (
    <Popover open={isOpen} modal={false}>
      <PopoverAnchor className="inline-block">{children}</PopoverAnchor>
      <PopoverContent
        align="center"
        side="top"
        sideOffset={10}
        className="w-auto p-1"
        onOpenAutoFocus={(e) => e.preventDefault()}
      >
        <IfElse
          if={category === 'time'}
          else={
            <div className="box-content flex h-9 items-center gap-1">
              <input
                ref={inputRef}
                defaultValue={value}
                onKeyDown={onInputKeyDown}
                className={cn(
                  inputVariants({ variant: 'normal', h: 'sm' }),
                  'min-w-8',
                  'max-w-32',
                  'w-min'
                )}
              />
              <ColorDropdownMenu>
                <Icons.colorPickPan
                  className={iconVariants({ variant: 'toolbar' })}
                />
              </ColorDropdownMenu>
              <Separator orientation="vertical" className="my-1" />
              <Button variant="ghost" size="sms" {...buttonProps}>
                <Icons.delete
                  className={iconVariants({ variant: 'toolbar' })}
                />
              </Button>
            </div>
          }
        >
          <StatusCalendar />
        </IfElse>
      </PopoverContent>
    </Popover>
  );
}
