import { Button, Input, message, Modal, Table, Tooltip } from 'antd';
import { Fragment, useEffect, useMemo, useState } from 'react';
import { useOrgStore } from '../store';
import { useShallow } from 'zustand/react/shallow';
import { Form } from 'antd';
import { useNewNavigate } from '@/modules';
import {
  EditOutlined,
  SettingOutlined,
  LinkOutlined,
  SaveOutlined,
  DeleteOutlined,
  LeftOutlined,
  PlusOutlined,
  SwapOutlined,
  UnorderedListOutlined,
} from '@ant-design/icons';
import clsx from 'clsx';
import { isObjectNull } from '@/utils/is-null';
import { CardBlank } from '@/components/card/CardBlank';
import { useLayoutStore } from '@/modules/layout/store';

const FormModal = () => {
  const [form] = Form.useForm();
  const userStore = useOrgStore(
    useShallow((state) => {
      return {
        showEdit: state.showEdit,
        setShowEdit: state.setShowEdit,
        formData: state.formData,
        updateData: state.updateData,
        setFormData: state.setFormData,
      };
    }),
  );
  useEffect(() => {
    const open = userStore.showEdit;
    if (open) {
      const isNull = isObjectNull(userStore.formData);
      if (isNull) {
        form.setFieldsValue({});
      } else form.setFieldsValue(userStore.formData);
    }
  }, [userStore.showEdit, userStore.formData]);
  const onFinish = async (values: any) => {
    userStore.updateData(values);
  };
  const onClose = () => {
    userStore.setShowEdit(false);
    form.setFieldsValue({});
    userStore.setFormData({});
  };
  const isEdit = userStore.formData.id;
  return (
    <Modal
      title={isEdit ? 'Edit' : 'Add'}
      open={userStore.showEdit}
      onClose={() => userStore.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='username' label='username'>
          <Input disabled={isEdit} />
        </Form.Item>
        <Form.Item name='description' label='description'>
          <Input.TextArea rows={4} />
        </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 = useNewNavigate();
  const userStore = useOrgStore(
    useShallow((state) => {
      return {
        setFormData: state.setFormData,
        setShowEdit: state.setShowEdit,
        list: state.list,
        deleteData: state.deleteData,
        getList: state.getList,
        loading: state.loading,
        updateData: state.updateData,
        formData: state.formData,
      };
    }),
  );
  const layoutStore = useLayoutStore(
    useShallow((state) => {
      return {
        switchOrg: state.switchOrg,
      };
    }),
  );
  const [codeEdit, setCodeEdit] = useState(false);
  const [code, setCode] = useState('');
  useEffect(() => {
    userStore.getList();
  }, []);

  const onAdd = () => {
    userStore.setFormData({});
    userStore.setShowEdit(true);
  };
  return (
    <div className='w-full h-full flex'>
      <div className='p-2'>
        <Button onClick={onAdd} icon={<PlusOutlined />}></Button>
      </div>
      <div className='flex flex-grow overflow-hidden h-full'>
        <div className='flex-grow overflow-auto scrollbar bg-gray-100'>
          <div className='flex  flex-wrap   gap-x-10 gap-y-4 rounded pt-10  justify-center'>
            {userStore.list.length > 0 &&
              userStore.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={() => {
                        setCode(item.code);
                        userStore.setFormData(item);
                        setCodeEdit(true);
                      }}>
                      <div className='px-4 cursor-pointer'>
                        <div
                          className='font-bold'
                          onClick={(e) => {
                            e.stopPropagation();
                            // message.success('copy code success');
                          }}>
                          {item.username || '-'}
                        </div>
                        <div className='font-light text-xs mt-2'>{item.description ? item.description : '-'}</div>
                      </div>
                      <div className='flex mt-2 '>
                        <Button.Group>
                          <Tooltip title='Edit'>
                            <Button
                              onClick={(e) => {
                                userStore.setFormData(item);
                                userStore.setShowEdit(true);
                                setCodeEdit(false);
                                e.stopPropagation();
                              }}
                              icon={<EditOutlined />}></Button>
                          </Tooltip>
                          <Tooltip title='User List'>
                            <Button
                              onClick={(e) => {
                                navicate(`/org/edit/user/${item.id}`);
                                e.stopPropagation();
                              }}
                              icon={<UnorderedListOutlined />}></Button>
                          </Tooltip>
                          <Button
                            onClick={(e) => {
                              Modal.confirm({
                                title: 'Delete',
                                content: 'Are you sure delete this data?',
                                onOk: () => {
                                  userStore.deleteData(item.id);
                                },
                              });
                              e.stopPropagation();
                            }}
                            icon={<DeleteOutlined />}></Button>
                          <Tooltip title='Switch to Org'>
                            <Button
                              icon={<SwapOutlined />}
                              onClick={() => {
                                layoutStore.switchOrg(item.username);
                              }}></Button>
                          </Tooltip>
                        </Button.Group>
                      </div>
                    </div>
                  </Fragment>
                );
              })}
            {userStore.list.length == 0 && <div className='text-center'>No Data</div>}
            <CardBlank className='w-[400px]' />
          </div>
        </div>
        <div className={clsx('bg-gray-100 border-l border-bg-slate-300 w-[600px] flex-shrink-0', !codeEdit && 'hidden', 'hidden')}>
          <div className='bg-white  p-2'>
            <div className='mt-2 ml-2 flex gap-2'>
              <Button
                onClick={() => {
                  setCodeEdit(false);
                  userStore.setFormData({});
                }}
                icon={<LeftOutlined />}></Button>
              <Button
                onClick={() => {
                  console.log('save', userStore.formData);
                  userStore.updateData({ ...userStore.formData, code });
                }}
                icon={<SaveOutlined />}></Button>
            </div>
          </div>
          <div className='h-[94%] p-2 rounded-2 shadow-sm'>
            <Input.TextArea
              value={code}
              onChange={(value) => {
                // setCode(value);
              }}
              className='h-full max-h-full scrollbar'
              style={{ overflow: 'auto' }}
            />
          </div>
        </div>
      </div>
      <FormModal />
    </div>
  );
};
