import { useNavigation, useParams } from 'react-router';
import { useAppVersionStore } from '../store';
import { useShallow } from 'zustand/react/shallow';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Button, Form, Input, message, Modal, Tooltip } from 'antd';
import { CloudUploadOutlined, DeleteOutlined, EditOutlined, FileOutlined, LeftOutlined, LinkOutlined, PlusOutlined } from '@ant-design/icons';
import { isObjectNull } from '@/utils/is-null';
import { FileUpload } from '../modules/FileUpload';
import clsx from 'clsx';
import { useNewNavigate } from '@/modules';
const FormModal = () => {
  const [form] = Form.useForm();
  const containerStore = useAppVersionStore(
    useShallow((state) => {
      return {
        showEdit: state.showEdit,
        setShowEdit: state.setShowEdit,
        formData: state.formData,
        updateData: state.updateData,
      };
    }),
  );
  useEffect(() => {
    const open = containerStore.showEdit;
    if (open) {
      if (open) {
        const isNull = isObjectNull(containerStore.formData);
        if (isNull) {
          form.setFieldsValue({});
        } else form.setFieldsValue(containerStore.formData);
      }
    }
  }, [containerStore.showEdit]);
  const onFinish = async (values: any) => {
    containerStore.updateData(values);
  };
  const onClose = () => {
    containerStore.setShowEdit(false);
    form.resetFields();
  };
  const isEdit = containerStore.formData.id;
  return (
    <Modal
      title={isEdit ? 'Edit' : 'Add'}
      open={containerStore.showEdit}
      onClose={() => containerStore.setShowEdit(false)}
      destroyOnClose
      footer={false}
      width={800}
      onCancel={onClose}>
      <Form
        form={form}
        onFinish={onFinish}
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 20,
        }}>
        <Form.Item name='id' hidden>
          <Input />
        </Form.Item>
        <Form.Item name='key' label='key'>
          <Input disabled />
        </Form.Item>
        <Form.Item name='version' label='version'>
          <Input />
        </Form.Item>
        <Form.Item label=' ' colon={false}>
          <Button type='primary' htmlType='submit'>
            Submit
          </Button>
          <Button className='ml-2' htmlType='reset' onClick={onClose}>
            Cancel
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export const AppVersionList = () => {
  const params = useParams();
  const appKey = params.appKey;
  const versionStore = useAppVersionStore(
    useShallow((state) => {
      return {
        list: state.list,
        getList: state.getList,
        key: state.key,
        setKey: state.setKey,
        setShowEdit: state.setShowEdit,
        formData: state.formData,
        setFormData: state.setFormData,
        deleteData: state.deleteData,
        publishVersion: state.publishVersion,
        app: state.app,
      };
    }),
  );
  const navigate = useNewNavigate();
  const [isUpload, setIsUpload] = useState(false);
  useEffect(() => {
    // fetch app version list
    if (appKey) {
      versionStore.setKey(appKey);
      versionStore.getList();
    }
  }, []);
  const appVersion = useMemo(() => {
    return versionStore.app?.version || '';
  }, [versionStore.app]);
  return (
    <div className='w-full h-full flex bg-slate-100'>
      <div className='p-2 bg-white'>
        <Button
          onClick={() => {
            versionStore.setFormData({ key: appKey });
            versionStore.setShowEdit(true);
          }}
          icon={<PlusOutlined />}
        />
      </div>

      <div className='flex-grow h-full relative'>
        <div className='absolute top-2 left-4'>
          <Tooltip title='返回' placement='bottom'>
            <Button
              onClick={() => {
                navigate('/app/edit/list');
              }}
              icon={<LeftOutlined />}
            />
          </Tooltip>
        </div>

        <div className='w-full h-full p-4 pt-12'>
          <div className='w-full h-full rounded-lg bg-white'>
            <div className='flex gap-2 flex-wrap p-4'>
              {versionStore.list.map((item, index) => {
                const isPublish = item.version === appVersion;
                const color = isPublish ? 'bg-green-500' : '';
                const isRunning = item.status === 'running';
                return (
                  <div className='card border-t w-[300px]' key={index}>
                    <div className={'flex items-center justify-between'}>
                      {item.version}

                      <Tooltip title={isPublish ? 'published' : ''}>
                        <div className={clsx('ml-4 rounded-full w-4 h-4', color)}></div>
                      </Tooltip>
                    </div>
                    <div className='mt-4'>
                      <Button.Group>
                        {/* <Button
                          onClick={() => {
                            versionStore.setFormData(item);
                            versionStore.setShowEdit(true);
                          }}
                          icon={<EditOutlined />}
                        /> */}
                        <Tooltip title='Delete'>
                          <Button
                            onClick={(e) => {
                              Modal.confirm({
                                title: 'Delete',
                                content: 'Are you sure delete this data?',
                                onOk: () => {
                                  versionStore.deleteData(item.id);
                                },
                              });
                              e.stopPropagation();
                            }}
                            icon={<DeleteOutlined />}
                          />
                        </Tooltip>
                        <Tooltip title='使用当前版本，发布为此版本'>
                          <Button
                            icon={<CloudUploadOutlined />}
                            onClick={() => {
                              versionStore.publishVersion({ id: item.id });
                            }}
                          />
                        </Tooltip>
                        <Tooltip title={'To Test App'}>
                          <Button
                            icon={<LinkOutlined />}
                            onClick={() => {
                              if (isRunning) {
                                let baseUri = 'https://kevisual.xiongxiao.me';
                                // if (DEV_SERVER) {
                                //   baseUri = 'http://localhost:3005';
                                // }
                                const link = new URL(`/test/${item.id}`, baseUri);
                                window.open(link.toString(), '_blank');
                              } else {
                                message.error('The app is not running');
                              }
                            }}></Button>
                        </Tooltip>
                        <Tooltip title='文件管理'>
                          <Button
                            icon={<FileOutlined />}
                            onClick={() => {
                              versionStore.setFormData(item);
                              setIsUpload(true);
                            }}
                          />
                        </Tooltip>
                      </Button.Group>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
      <div className='flex-shrink h-full'>
        {isUpload && (
          <div className='bg-white p-2 w-[600px] h-full flex flex-col'>
            <div className='header flex items-center gap-2'>
              <Tooltip title='返回'>
                <Button
                  onClick={() => {
                    setIsUpload(false);
                  }}
                  icon={<LeftOutlined />}
                />
              </Tooltip>
              <div className='font-bold'>{versionStore.key}</div>
            </div>
            <AppVersionFile />
          </div>
        )}
      </div>
      <FormModal />
    </div>
  );
};
export const AppVersionFile = () => {
  const versionStore = useAppVersionStore(
    useShallow((state) => {
      return {
        formData: state.formData,
      };
    }),
  );
  const versionFiles = useMemo(() => {
    if (!versionStore.formData?.data) return [];
    const files = versionStore.formData.data.files || [];
    return files;
  }, [versionStore.formData]);
  return (
    <>
      <div>version: {versionStore.formData.version}</div>
      <div className='border rounded-md my-2 flex-grow overflow-hidden'>
        <div className='flex gap-2 items-center border-b py-2 px-2'>
          Files
          <FileUpload />
        </div>
        <div
          className='mt-2 '
          style={{
            height: 'calc(100% - 40px)',
          }}>
          <div className='h-full overflow-auto mb-4 pb-8 scrollbar'>
            {versionFiles.map((file, index) => {
              const prefix = versionStore.formData.key + '/' + versionStore.formData.version + '/';
              const _path = file.path || '';
              const path = _path.replace(prefix, '');
              return (
                <div className='flex gap-2 px-4 py-2 border-b' key={index}>
                  {/* <div className='w-[100px] truncate'>{file.name}</div> */}
                  <div>
                    <FileOutlined />
                  </div>
                  <div>{path}</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </>
  );
};
