import {
  createRef,
  forwardRef,
  useImperativeHandle,
  useState,
} from 'react';

import { LuTrash2 } from 'react-icons/lu';
import { MdClose } from 'react-icons/md';

import {
  mFastAnswers,
  rpc,
} from '../api/request';
import { ShmFastAnswerType } from '../api/types';
import store from '../stores/store';
import Button from '../ui/Button';
import Header from '../ui/Header';
import IconButton from '../ui/IconButton';
import Input from '../ui/Input';
import { showAlert } from './AlertRoot';

export type FastAnswerPopupRootRefProps = {
  open: (fastAnswer?: ShmFastAnswerType) => void;
  close: () => void;
};

export const fastAnswerPopupRootRef = createRef<FastAnswerPopupRootRefProps>();

const FastAnswerPopupRoot = forwardRef<FastAnswerPopupRootRefProps>((_, ref) => {
  const [opened, setOpened] = useState(false);
  const [fastAnswer, setFastAnswer] = useState<ShmFastAnswerType>({
    name: '',
    text: '',
  });

  useImperativeHandle(ref, () => ({
    open: (fa) => {
      setOpened(true);
      setFastAnswer(fa ?? { name: '', text: '' });
    },
    close: () => setOpened(false),
  }));

  if (!opened) return null;

  return (
    <div className="fixed inset-0 z-[250] flex flex-col bg-[var(--tg-bg)] tg-slide-up">
      <Header
        left={
          <IconButton onClick={() => setOpened(false)}>
            <MdClose />
          </IconButton>
        }
        center={<div className="text-[17px] font-semibold pl-2">Быстрый ответ</div>}
      />

      <div className="flex-1 overflow-y-auto tg-scroll p-4 space-y-3">
        <Input
          label="Название"
          placeholder="Введите название"
          value={fastAnswer.name ?? ''}
          onChange={(v) => setFastAnswer((p) => ({ ...p, name: v }))}
        />
        <Input
          label="Текст"
          placeholder="Введите текст быстрого ответа"
          value={fastAnswer.text ?? ''}
          onChange={(v) => setFastAnswer((p) => ({ ...p, text: v }))}
          multiline
          rows={5}
        />
      </div>

      <div className="shrink-0 px-4 py-3 border-t border-[var(--tg-divider)] flex gap-2">
        <Button
          fullWidth
          disabled={!fastAnswer.name || !fastAnswer.text}
          onClick={() => {
            rpc
              .mFastAnswers({
                id: fastAnswer._id,
                name: fastAnswer.name,
                text: fastAnswer.text,
              })
              .then(() => {
                store.loadFastAnswers();
                setOpened(false);
              });
          }}
        >
          Сохранить
        </Button>

        {!!fastAnswer._id && (
          <Button
            variant="danger"
            onClick={() => {
              showAlert({
                title: 'Удалить быстрый ответ?',
                content: 'Это действие нельзя отменить.',
                buttons: [
                  {
                    text: 'Удалить',
                    variant: 'danger',
                    onClick: () => {
                      mFastAnswers({
                        delete: true,
                        id: fastAnswer._id,
                      }).then(() => {
                        store.loadFastAnswers();
                        setOpened(false);
                      });
                    },
                  },
                  { text: 'Отмена' },
                ],
              });
            }}
          >
            <LuTrash2 size={18} />
          </Button>
        )}
      </div>
    </div>
  );
});

FastAnswerPopupRoot.displayName = 'FastAnswerPopupRoot';

export default FastAnswerPopupRoot;
