import { ITreeItem } from '@/api';
import Card from '@/components/Card';
import DragTree from '@/components/Drag/DragTree';
import { postApiV1KnowledgeBaseRelease } from '@/request/KnowledgeBase';
import { getApiV1NodeList } from '@/request/Node';
import { DomainNodeListItemResp } from '@/request/types';
import { useAppSelector } from '@/store';
import { convertToTree } from '@/utils/drag';
import { message, Modal } from '@ctzhian/ui';
import { Box, Checkbox, Stack, TextField } from '@mui/material';
import dayjs from 'dayjs';
import { useEffect, useMemo, useState } from 'react';
import { Controller, useForm } from 'react-hook-form';

interface VersionPublishProps {
  open: boolean;
  defaultSelected?: string[];
  onClose: () => void;
  refresh: () => void;
}

const VersionPublish = ({
  open,
  defaultSelected = [],
  onClose,
  refresh,
}: VersionPublishProps) => {
  const { kb_id } = useAppSelector(state => state.config);

  const [selected, setSelected] = useState<string[]>([]);
  const [folderIds, setFolderIds] = useState<string[]>([]);
  const [treeList, setTreeList] = useState<ITreeItem[]>([]);
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<DomainNodeListItemResp[]>([]);

  const {
    handleSubmit,
    control,
    formState: { errors },
    reset,
    setValue,
  } = useForm({
    defaultValues: {
      tag: '',
      message: '',
    },
  });

  const getData = () => {
    getApiV1NodeList({ kb_id }).then(res => {
      const unPublishedData = res?.filter(item => item.status === 1) || [];
      setList(unPublishedData);
      setSelected(
        defaultSelected.length > 0
          ? defaultSelected
          : unPublishedData.map(it => it.id!),
      );
      const showTreeData = convertToTree(unPublishedData || []);
      setTreeList(showTreeData);
      setFolderIds(res.filter(item => item.type === 1).map(item => item.id!));
    });
  };

  const onSubmit = handleSubmit(data => {
    if (selected.length > 0) {
      postApiV1KnowledgeBaseRelease({
        kb_id,
        ...data,
        node_ids: [...selected, ...folderIds],
      }).then(() => {
        message.success(`${data.tag} 版本发布成功`);
        reset();
        setSelected([]);
        onClose();
        refresh();
      });
    } else {
      message.error(total > 0 ? '请选择要发布的文档' : '暂无未发布文档');
    }
  });

  useEffect(() => {
    if (open) {
      getData();
      setValue(
        'tag',
        `${dayjs().format('YYYYMMDD')}-${Math.random().toString(36).substring(2, 8)}`,
      );
      setValue(
        'message',
        `${dayjs().format('YYYY 年 MM 月 DD 日 HH 时 mm 分 ss 秒')}发布`,
      );
    }
  }, [open, kb_id]);

  const selectedTotal = useMemo(() => {
    return list.filter(item => selected.includes(item.id!)).length;
  }, [selected, list]);

  return (
    <Modal title='发布新版本' open={open} onCancel={onClose} onOk={onSubmit}>
      <>
        <Box sx={{ fontSize: 14, lineHeight: '32px' }}>
          版本号
          <Box component='span' sx={{ color: 'error.main', ml: 0.5 }}>
            *
          </Box>
        </Box>
        <Controller
          control={control}
          name='tag'
          rules={{ required: '版本号不能为空' }}
          render={({ field }) => (
            <TextField
              {...field}
              fullWidth
              size='small'
              placeholder='请输入版本号'
              error={!!errors.tag}
              helperText={errors.tag?.message}
            />
          )}
        />
        <Box sx={{ fontSize: 14, lineHeight: '32px', mt: 1 }}>
          版本描述
          <Box component='span' sx={{ color: 'error.main', ml: 0.5 }}>
            *
          </Box>
        </Box>
        <Controller
          control={control}
          name='message'
          rules={{ required: '版本描述不能为空' }}
          render={({ field }) => (
            <TextField
              {...field}
              fullWidth
              multiline
              rows={2}
              size='small'
              placeholder='请输入版本描述'
              error={!!errors.message}
              helperText={errors.message?.message}
            />
          )}
        />
        <Stack
          direction='row'
          component='label'
          alignItems={'center'}
          justifyContent={'space-between'}
          gap={1}
          sx={{
            py: 1,
            pr: 2,
            cursor: 'pointer',
            borderRadius: '10px',
            fontSize: 14,
            mt: 1,
          }}
        >
          <Box>
            未发布文档/文件夹
            <Box
              component='span'
              sx={{ color: 'text.tertiary', fontSize: 12, pl: 1 }}
            >
              共 {list.length} 个，已选中 {selectedTotal} 个
            </Box>
          </Box>
          <Stack direction='row' alignItems={'center'}>
            <Box sx={{ color: 'text.tertiary', fontSize: 12 }}>全选</Box>
            <Checkbox
              size='small'
              sx={{
                p: 0,
                color: 'text.disabled',
                width: '35px',
                height: '35px',
              }}
              checked={selectedTotal === list.length}
              onChange={() => {
                setSelected(
                  selectedTotal === list.length
                    ? []
                    : list.map(item => item.id!),
                );
              }}
            />
          </Stack>
        </Stack>
        <Card sx={{ bgcolor: 'background.paper3', py: 1 }}>
          <Stack
            gap={0.25}
            sx={{
              fontSize: 14,
              maxHeight: 'calc(100vh - 520px)',
              overflowY: 'auto',
              px: 2,
            }}
          >
            <DragTree
              ui='select'
              readOnly
              selected={selected}
              data={treeList}
              refresh={getData}
              onSelectChange={ids => setSelected(ids)}
            />
          </Stack>
        </Card>
      </>
    </Modal>
  );
};

export default VersionPublish;
