import { Fragment, Suspense, useEffect, useState } from 'react';
import { useContainerStore } from '../store';
import { useShallow } from 'zustand/react/shallow';
// import copy from 'copy-to-clipboard';
import { useNewNavigate } from '@/modules';
import { message } from '@/modules/message';
import { Dialog, DialogTitle, DialogContent, Tooltip, Button, ButtonGroup } from '@mui/material';
import { IconButton } from '@kevisual/components/button/index.tsx';
import { getDirectoryAndName, toFile, uploadFileChunked } from '@kevisual/resources/index.ts';
import EditOutlined from '@ant-design/icons/EditOutlined';
import DeleteOutlined from '@ant-design/icons/DeleteOutlined';
import PlusOutlined from '@ant-design/icons/PlusOutlined';
import CloudUploadOutlined from '@ant-design/icons/CloudUploadOutlined';

import { isObjectNull } from '@/utils/is-null';
import { CardBlank } from '@/components/card/CardBlank';
import { Settings } from 'lucide-react';
import React from 'react';
import { useModal } from '@kevisual/components/modal/Confirm.tsx';
import { useForm, Controller } from 'react-hook-form';
import { TextField } from '@mui/material';
import { pick } from 'lodash-es';
import { useTranslation } from 'react-i18next';
import { TagsInput } from '@kevisual/components/select/TagsInput.tsx';
const DrawEdit = React.lazy(() => import('../module/DrawEdit'));

const FormModal = () => {
  const { control, handleSubmit, reset, setValue } = useForm();
  const containerStore = useContainerStore(
    useShallow((state) => {
      return {
        showEdit: state.showEdit,
        setShowEdit: state.setShowEdit,
        formData: state.formData,
        updateData: state.updateData,
      };
    }),
  );

  useEffect(() => {
    const open = containerStore.showEdit;
    if (open) {
      const isNull = isObjectNull(containerStore.formData);
      if (isNull) {
        reset({});
      } else {
        Object.keys(containerStore.formData).forEach((key) => {
          setValue(key, containerStore.formData[key]);
        });
      }
    }
    return () => {
      reset({});
    };
  }, [containerStore.showEdit]);

  const onFinish = async (values: any) => {
    const pickValues = pick(values, ['id', 'title', 'description', 'tags', 'code']);
    containerStore.updateData(pickValues);
  };

  const onClose = () => {
    containerStore.setShowEdit(false);
    reset();
  };

  const isEdit = containerStore.formData.id;
  const { t } = useTranslation();
  return (
    <Dialog open={containerStore.showEdit} onClose={onClose}>
      <DialogTitle>{isEdit ? 'Edit' : 'Add'}</DialogTitle>
      <DialogContent sx={{ padding: '20px', minWidth: '600px' }}>
        <form className='flex flex-col gap-6 pt-2' onSubmit={handleSubmit(onFinish)}>
          <Controller name='title' control={control} defaultValue='' render={({ field }) => <TextField {...field} label='Title' fullWidth />} />
          <Controller
            name='description'
            control={control}
            defaultValue=''
            render={({ field }) => <TextField {...field} label='Description' multiline rows={4} fullWidth />}
          />
          <Controller
            name='tags'
            control={control}
            defaultValue={[]}
            render={({ field }) => {
              return <TagsInput key={'tags'} showLabel label={t('Tags')} value={field.value} onChange={(value) => field.onChange(value)} />;
            }}
          />
          {!isEdit && (
            <Controller name='code' control={control} defaultValue='' render={({ field }) => <TextField {...field} label='Code' multiline fullWidth />} />
          )}
          <div>
            <Button variant='contained' type='submit'>
              {t('Submit')}
            </Button>
            <Button className='ml-2' onClick={onClose}>
              {t('Cancel')}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
};
const PublishFormModal = () => {
  const { control, handleSubmit, reset, setValue, getValues } = useForm();
  const { t } = useTranslation();
  const containerStore = useContainerStore(
    useShallow((state) => {
      return {
        showEdit: state.showPublish,
        setShowEdit: state.setShowPublish,
        formData: state.formData,
        updateData: state.updateData,
      };
    }),
  );

  useEffect(() => {
    const open = containerStore.showEdit;
    if (open) {
      const isNull = isObjectNull(containerStore.formData);
      if (isNull) {
        reset({});
      } else {
        Object.keys(containerStore.formData).forEach((key) => {
          setValue(key, containerStore.formData[key]);
        });
      }
    }
  }, [containerStore.showEdit]);

  const onFinish = async () => {
    const values = getValues();
    const pickValues = pick(values, ['id', 'publish.key', 'publish.version', 'publish.fileName', 'publish.description']);
    const containerRes = await containerStore.updateData(pickValues, { closePublish: false });
    if (containerRes.code === 200) {
      const code = containerRes.data?.code || '-';
      const fileName = values['publish']?.['fileName'];
      let directoryAndName: ReturnType<typeof getDirectoryAndName> | null = null;
      try {
        directoryAndName = getDirectoryAndName(fileName);
        if (!directoryAndName) {
          message.error('Invalid filename');
          return;
        }
      } catch (error) {
        message.error('Invalid filename');
        return;
      }

      const key = values['publish']['key'];
      const version = values['publish']['version'];
      const file = toFile(code, directoryAndName.name);
      const res = (await uploadFileChunked(file, {
        appKey: key,
        version,
        directory: directoryAndName.directory,
      })) as any;
      if (res.code === 200) {
        message.success('upload success');
      } else {
        message.error('upload failed');
      }
    }
  };

  const onUpdate = async () => {
    const values = getValues();
    containerStore.updateData(values);
  };

  const onClose = () => {
    containerStore.setShowEdit(false);
    reset();
  };

  return (
    <Dialog open={containerStore.showEdit} onClose={onClose}>
      <DialogTitle>Publish</DialogTitle>
      <DialogContent sx={{ padding: '10px', minWidth: '600px' }}>
        <form className='flex flex-col gap-6 pt-2' onSubmit={handleSubmit(onFinish)}>
          <Controller
            name='publish.key'
            control={control}
            defaultValue=''
            render={({ field }) => <TextField {...field} label='App key' required fullWidth />}
          />
          <Controller
            name='publish.version'
            control={control}
            defaultValue=''
            render={({ field }) => <TextField {...field} label='App Version' required fullWidth />}
          />
          <Controller
            name='publish.fileName'
            control={control}
            defaultValue=''
            render={({ field }) => <TextField {...field} label='Filename' required fullWidth />}
          />
          <Controller
            name='publish.description'
            control={control}
            defaultValue=''
            render={({ field }) => <TextField {...field} label='Description' multiline rows={4} fullWidth />}
          />
          <div className='flex gap-3'>
            <Tooltip
              placement='top'
              title='根据文件名和code的字符串的内容，自动生成文件。并保存。如果是其他文件类型，转成base64上传。比如图片以类似data:image/jpeg;开头'>
              <Button variant='contained' color='primary' type='submit'>
                {t('Upload')}
              </Button>
            </Tooltip>
            <Button variant='contained' onClick={onUpdate}>
              {t('Submit')}
            </Button>
            <Button onClick={onClose}>{t('Cancel')}</Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
};
export const ContainerList = () => {
  const navicate = useNewNavigate();
  const [modal, contextHolder] = useModal();
  const containerStore = useContainerStore(
    useShallow((state) => {
      return {
        setFormData: state.setFormData,
        setShowEdit: state.setShowEdit,
        list: state.list,
        deleteData: state.deleteData,
        getList: state.getList,
        loading: state.loading,
        // publishData: state.publishData,
        setShowPublish: state.setShowPublish,
        updateData: state.updateData,
        formData: state.formData,
        getOne: state.getOne,
        setOpenDrawEdit: state.setOpenDrawEdit,
        openDrawEdit: state.openDrawEdit,
      };
    }),
  );

  // const [codeEdit, setCodeEdit] = useState(false);
  useEffect(() => {
    containerStore.getList();
  }, []);

  const onAdd = () => {
    containerStore.setFormData({});
    containerStore.setShowEdit(true);
  };

  return (
    <div className='w-full h-full flex '>
      <div className='p-2 flex flex-col gap-2'>
        <Tooltip title='添加'>
          <IconButton variant='contained' onClick={onAdd}>
            <PlusOutlined />
          </IconButton>
        </Tooltip>
      </div>
      <div className='flex grow overflow-hidden h-full'>
        <div className='grow overflow-auto scrollbar bg-gray-100'>
          <div className='flex  flex-wrap   gap-x-10 gap-y-4 rounded-sm pt-10  justify-center'>
            {containerStore.list.length > 0 &&
              containerStore.list.map((item) => {
                return (
                  <Fragment key={item.id}>
                    <div
                      className='flex text-sm gap flex-col w-[400px] max-h-[400px] bg-white p-4 rounded-lg'
                      key={item.id}
                      onClick={() => {
                        // containerStore.setFormData(item);
                      }}>
                      <div className='px-4 cursor-pointer'>
                        <div
                          className='font-bold flex items-center'
                          onClick={(e) => {
                            e.stopPropagation();
                          }}>
                          {item.title || '-'}
                          <div className='font-thin card-key ml-3'>{item.tags ? item.tags?.join?.(', ') : ''}</div>
                        </div>
                        <div className='font-light text-xs mt-2'>{item.description ? item.description : '-'}</div>
                      </div>

                      <div className='flex mt-2 '>
                        <ButtonGroup
                          variant='contained'
                          color='primary'
                          sx={{ color: 'white', '& .MuiButton-root': { color: 'white', minWidth: '32px', width: '32px', height: '32px', padding: '6px' } }}>
                          <Tooltip title='编辑代码'>
                            <Button
                              onClick={(e) => {
                                containerStore.getOne(item.id);
                                containerStore.setFormData(item);
                                containerStore.setOpenDrawEdit(true);
                                e.stopPropagation();
                              }}>
                              <Settings size={16} />
                            </Button>
                          </Tooltip>
                          <Tooltip title='编辑'>
                            <Button
                              onClick={(e) => {
                                containerStore.setFormData(item);
                                containerStore.setShowEdit(true);
                                e.stopPropagation();
                              }}>
                              <EditOutlined />
                            </Button>
                          </Tooltip>
                          <Tooltip title='添加到 user app当中'>
                            <Button
                              onClick={(e) => {
                                // containerStore.publishData(item);
                                containerStore.setFormData(item);
                                containerStore.setShowPublish(true);
                                e.stopPropagation();
                              }}>
                              <CloudUploadOutlined />
                            </Button>
                          </Tooltip>
                          <Tooltip title='删除'>
                            <Button
                              // color='error'
                              onClick={(e) => {
                                e.stopPropagation();
                                modal.confirm({
                                  title: 'Delete',
                                  content: 'Are you sure delete this data?',
                                  onOk: () => {
                                    containerStore.deleteData(item.id);
                                  },
                                });
                                e.stopPropagation();
                              }}>
                              <DeleteOutlined />
                            </Button>
                          </Tooltip>
                        </ButtonGroup>
                      </div>
                    </div>
                  </Fragment>
                );
              })}
            {containerStore.list.length == 0 && (
              <div className='text-center' key={'no-data'}>
                No Data
              </div>
            )}
            <CardBlank className='w-[400px]' />
          </div>
        </div>
      </div>
      <Suspense fallback={<div></div>}>
        <DrawEdit />
      </Suspense>
      <PublishFormModal />
      <FormModal />
      {contextHolder}
    </div>
  );
};
