import { Button, Input, message, Modal, Select, Table, Tooltip } from 'antd';
import { Fragment, useEffect, useMemo, useState } from 'react';
import { TextArea } from '../components/TextArea';
import { useContainerStore } from '../store';
import { useShallow } from 'zustand/react/shallow';
import { Form } from 'antd';
import copy from 'copy-to-clipboard';
import { useNewNavigate } from '@/modules';
import {
  EditOutlined,
  SettingOutlined,
  LinkOutlined,
  SaveOutlined,
  DeleteOutlined,
  LeftOutlined,
  MessageOutlined,
  PlusOutlined,
  DashboardOutlined,
} from '@ant-design/icons';
import clsx from 'clsx';
import { isObjectNull } from '@/utils/is-null';
import { CardBlank } from '@/components/card/CardBlank';
import { useAiStore } from '@/pages/ai-chat';
const FormModal = () => {
  const [form] = Form.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) {
      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='title' label='title'>
          <Input />
        </Form.Item>
        <Form.Item name='description' label='description'>
          <Input.TextArea rows={4} />
        </Form.Item>
        <Form.Item name='tags' label='tags'>
          <Select mode='tags' />
        </Form.Item>
        <Form.Item name='code' label='code'>
          <TextArea />
        </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 ContainerList = () => {
  const navicate = useNewNavigate();
  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,
        updateData: state.updateData,
        formData: state.formData,
      };
    }),
  );
  const aiStore = useAiStore(
    useShallow((state) => {
      return {
        open: state.open,
        setOpen: state.setOpen,
        setKey: state.setKey,
      };
    }),
  );
  const [codeEdit, setCodeEdit] = useState(false);
  const [code, setCode] = useState('');
  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='add'>
          <Button onClick={onAdd} icon={<PlusOutlined />}></Button>
        </Tooltip>
        <Tooltip title='To Panel'>
          <Button onClick={() => navicate('/panel')} icon={<DashboardOutlined />}></Button>
        </Tooltip>
      </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'>
            {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={() => {
                        setCode(item.code);
                        containerStore.setFormData(item);
                        setCodeEdit(true);
                      }}>
                      <div className='px-4 cursor-pointer'>
                        <div
                          className='font-bold flex items-center'
                          onClick={(e) => {
                            copy(item.code);
                            e.stopPropagation();
                            message.success('copy code success');
                          }}>
                          {item.title || '-'}
                          <div className='font-thin card-key ml-3 text-xs'>{item.tags ? item.tags.join(', ') : ''}</div>
                        </div>
                        <div className='font-light text-xs mt-2'>{item.description ? item.description : '-'}</div>
                      </div>
                      <div className='w-full text-xs'>
                        <TextArea className='max-h-[240px] scrollbar' value={item.code} readonly />
                      </div>
                      <div className='flex mt-2 '>
                        <Button.Group>
                          <Button
                            onClick={() => {
                              // containerStore.publishData(item);
                            }}
                            icon={<SettingOutlined />}></Button>
                          <Button
                            onClick={(e) => {
                              containerStore.setFormData(item);
                              containerStore.setShowEdit(true);
                              setCodeEdit(false);
                              e.stopPropagation();
                            }}
                            icon={<EditOutlined />}></Button>
                          <Button
                            onClick={(e) => {
                              // navicate('/container/preview/' + item.id);
                              window.open('/container/preview/' + item.id);
                              e.stopPropagation();
                            }}
                            icon={<LinkOutlined />}></Button>
                          <Button
                            onClick={(e) => {
                              e.stopPropagation();
                              Modal.confirm({
                                title: 'Delete',
                                content: 'Are you sure delete this data?',
                                onOk: () => {
                                  containerStore.deleteData(item.id);
                                },
                              });
                              e.stopPropagation();
                            }}
                            icon={<DeleteOutlined />}></Button>
                        </Button.Group>
                      </div>
                    </div>
                  </Fragment>
                );
              })}
            {containerStore.list.length == 0 && (
              <div className='text-center' key={'no-data'}>
                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')}>
          <div className='bg-white  p-2'>
            <div className='mt-2 ml-2 flex gap-2'>
              <Tooltip title='返回'>
                <Button
                  onClick={() => {
                    setCodeEdit(false);
                    containerStore.setFormData({});
                  }}
                  icon={<LeftOutlined />}></Button>
              </Tooltip>
              <Tooltip title='保存'>
                <Button
                  onClick={() => {
                    console.log('save', containerStore.formData);
                    containerStore.updateData({ ...containerStore.formData, code });
                  }}
                  icon={<SaveOutlined />}></Button>
              </Tooltip>
              <Tooltip title='预览'>
                <Button
                  onClick={(e) => {
                    // navicate('/container/preview/' + item.id);
                    e.stopPropagation();
                  }}
                  icon={<LinkOutlined />}></Button>
              </Tooltip>
              <Tooltip title='ai编程'>
                <Button
                  onClick={(e) => {
                    aiStore.setKey(location.pathname);
                    aiStore.setOpen(true);
                  }}
                  icon={<MessageOutlined />}></Button>
              </Tooltip>
            </div>
          </div>
          <div className='h-[94%] p-2 rounded-2 shadow-sm'>
            <TextArea
              value={code}
              onChange={(value) => {
                setCode(value);
              }}
              className='h-full max-h-full scrollbar'
              style={{ overflow: 'auto' }}
            />
          </div>
        </div>
      </div>
      <FormModal />
    </div>
  );
};
