import { useEditStore } from '../store';
import { Button, Input, message, Modal, Table, Tooltip } from 'antd';
import { useEffect, useState } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { Form } from 'antd';
import copy from 'copy-to-clipboard';
import { useNavigate } from 'react-router';
import { useToCodeEditor } from '@/pages/code-editor';
import { CardBlank } from '@/components/card/CardBlank';
import {
  AppstoreFilled,
  AppstoreOutlined,
  ArrowRightOutlined,
  CloudDownloadOutlined,
  CloudUploadOutlined,
  CodeOutlined,
  DeleteOutlined,
  EditOutlined,
  ForkOutlined,
  GoldOutlined,
  PlusOutlined,
  RocketFilled,
  RollbackOutlined,
  ToolOutlined,
} from '@ant-design/icons';
import { isObjectNull } from '@/utils/is-null';
import { PublishFormModal } from './modal/PublishFormModal';

const FormModal = () => {
  const [form] = Form.useForm();
  const editStore = useEditStore(
    useShallow((state) => {
      return {
        showEdit: state.showEditModal,
        setShowEdit: state.setShowEditModal,
        formData: state.formData,
        setFormData: state.setFormData,
        updateData: state.updateData,
      };
    }),
  );
  useEffect(() => {
    const open = editStore.showEdit;
    if (open) {
      if (isObjectNull(editStore.formData.data)) {
        form.setFieldsValue({});
      } else form.setFieldsValue(editStore.formData);
    }
  }, [editStore.showEdit]);
  const onFinish = async (values: any) => {
    let defaultData = {
      nodes: [],
      edges: [],
      viewport: {},
    };
    if (!isEdit) {
      values.data = defaultData;
    }
    editStore.updateData(values);
  };
  const onClose = () => {
    editStore.setShowEdit(false);
    form.resetFields();
    editStore.setFormData({});
  };
  const isEdit = editStore.formData.id;
  return (
    <Modal title={isEdit ? 'Edit' : 'Add'} open={editStore.showEdit} onClose={onClose} 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='title' label='title'>
          <Input />
        </Form.Item>
        <Form.Item name='description' label='description'>
          <Input.TextArea lang={'markdown'} />
        </Form.Item>
        <Form.Item name='type' label='type' noStyle hidden>
          <Input />
        </Form.Item>
        <Form.Item name='data' label='data' noStyle hidden>
          <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 List = () => {
  const navicate = useNavigate();
  const toCodeEditor = useToCodeEditor();
  const editStore = useEditStore(
    useShallow((state) => {
      return {
        setFormData: state.setFormData,
        setShowEdit: state.setShowEditModal,
        list: state.list,
        deleteData: state.deleteData,
        getList: state.getList,
        loading: state.loading,
        setShowPublishModal: state.setShowPublishModal,
        downloadData: state.downloadData,
      };
    }),
  );
  useEffect(() => {
    editStore.getList();
  }, []);

  return (
    <div className='w-full h-full flex bg-gray-200'>
      <div className='p-2 bg-white rounded-r-lg flex flex-col gap-2'>
        <Tooltip title='Add'>
          <Button
            className='w-10 '
            icon={<PlusOutlined />}
            onClick={() => {
              editStore.setFormData({});
              editStore.setShowEdit(true);
            }}></Button>
        </Tooltip>
        <Tooltip title='To App'>
          <Button
            onClick={() => {
              navicate('/app');
            }}
            icon={<AppstoreOutlined />}></Button>
        </Tooltip>
        <Tooltip title='To Container'>
          <Button
            onClick={() => {
              navicate('/container');
            }}
            icon={<CodeOutlined />}></Button>
        </Tooltip>
      </div>
      <div className='flex-grow overflow-scroll scrollbar mt-4'>
        <div className=''>
          <div className=' flex flex-wrap gap-10 justify-center h-full overflow-auto scrollbar'>
            {editStore.list.length > 0 &&
              editStore.list.map((item, index) => {
                const publish = item.publish;
                if (publish.id) {
                  console.log(item, item.publish);
                }
                return (
                  <div className='card w-[300px]' key={index}>
                    <div className='card-title'>{item.title}</div>
                    <div className='card-subtitle'> {item.description}</div>
                    <div className='mt-4'>
                      <Button.Group>
                        <Tooltip title='Edit'>
                          <Button
                            onClick={() => {
                              editStore.setFormData(item);
                              editStore.setShowEdit(true);
                            }}
                            icon={<EditOutlined />}
                          />
                        </Tooltip>
                        <Tooltip title='to flow'>
                          <Button
                            onClick={() => {
                              navicate('/panel/flow/' + item.id);
                            }}
                            icon={<ForkOutlined />}
                          />
                        </Tooltip>
                        <Tooltip title='to deck'>
                          <Button
                            onClick={() => {
                              navicate('/panel/deck/' + item.id);
                            }}
                            icon={<GoldOutlined />}
                          />
                        </Tooltip>
                        <Tooltip title='to code editor'>
                          <Button
                            onClick={() => {
                              toCodeEditor.toPagePage(item);
                            }}
                            icon={<ToolOutlined />}
                          />
                        </Tooltip>
                        <Tooltip title='Publish'>
                          <Button
                            onClick={() => {
                              editStore.setFormData(item);
                              editStore.setShowPublishModal(true);
                            }}
                            icon={<CloudUploadOutlined />}
                          />
                        </Tooltip>
                        {item.publish?.id && (
                          <Tooltip title={`转到${item?.publish.key || ''} App Version List`}>
                            <Button
                              onClick={() => {
                                const app = '/app/' + item?.publish?.key + '/version/list';
                                navicate(app);
                              }}
                              icon={<ArrowRightOutlined />}
                            />
                          </Tooltip>
                        )}
                        <Tooltip title='Download'>
                          <Button
                            onClick={() => {
                              editStore.downloadData(item.id);
                            }}
                            icon={<CloudDownloadOutlined />}
                          />
                        </Tooltip>
                        <Tooltip title='delete'>
                          <Button
                            onClick={(e) => {
                              Modal.confirm({
                                title: 'Delete',
                                content: 'Are you sure delete this data?',
                                onOk: () => {
                                  editStore.deleteData(item.id);
                                },
                              });
                              e.stopPropagation();
                            }}
                            icon={<DeleteOutlined />}
                          />
                        </Tooltip>
                      </Button.Group>
                    </div>
                  </div>
                );
              })}
            {editStore.list.length === 0 && <div className='text-center text-gray-500'>No data</div>}
            <CardBlank className='w-[300px]' />
          </div>
        </div>
      </div>
      <FormModal />
      <PublishFormModal />
    </div>
  );
};
