import { isObjectNull } from '@/utils/is-null';
import { Button, Form, Input, message, Modal, Select } from 'antd';
import { useEffect, useState } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { useDeckPageStore } from './deck-store';
export const FormModal = () => {
  const [form] = Form.useForm();
  const [options, setOptions] = useState<{ label: string; value: any }[]>([]);
  const deckPageStore = useDeckPageStore(
    useShallow((state) => {
      return {
        showEdit: state.showEdit,
        setShowEdit: state.setShowEdit,
        pageData: state.pageData,
        getPageData: state.getPageData,
        formData: state.formData,
        setFormData: state.setFormData,
        id: state.id,
        setSelected: state.setSelected,
        getSeleted: state.getSeleted,
      };
    }),
  );
  useEffect(() => {
    if (!deckPageStore.showEdit) return;
    const pageData = deckPageStore.getPageData() || [];
    const data = pageData.map((item) => {
      const { container } = item?.data || {};
      const label = container?.title;
      return {
        label: label || item.id,
        value: item.id,
      };
    });
    setOptions(data);
    const selected = deckPageStore.getSeleted();
    const { cid } = selected?.data || {};
    if (cid) {
      form.setFieldsValue({ cid });
      return;
    }
    const isNull = isObjectNull(deckPageStore.formData);
    if (isNull) {
      form.setFieldsValue({});
      form.resetFields();
    } else {
      form.setFieldsValue(deckPageStore.formData);
    }
  }, [deckPageStore.showEdit, deckPageStore.pageData]);
  const onFinish = async (values: any) => {
    const pageData = deckPageStore.getPageData() || [];
    const page = pageData.find((item) => item.id === values.cid);
    if (!page) {
      message.error('Page not found');
      return;
    }
    const cid = values.cid;
    if (!cid) {
      return;
    }
    const el = document.querySelector(`[data-cid="${values.cid}"]`);
    if (el) {
      const data = (el as HTMLDivElement).dataset;
      const { cid, pid } = data;
      document.querySelectorAll('.active').forEach((item) => {
        item.classList.remove('active');
      });
      el.classList.add('active');
      // el.scrollIntoView({ behavior: 'smooth', });
      deckPageStore.setSelected({ type: 'active', data: { cid, pid, rid: deckPageStore.id } });
    }
    onClose();
  };
  const onClose = () => {
    deckPageStore.setShowEdit(false);
    deckPageStore.setFormData({});
    form.setFieldsValue({});
  };
  return (
    <Modal
      title={'Select a element'}
      open={deckPageStore.showEdit}
      onClose={() => deckPageStore.setShowEdit(false)}
      destroyOnClose
      footer={false}
      width={800}
      onCancel={onClose}>
      <Form
        className='mt-4'
        form={form}
        onFinish={onFinish}
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 20,
        }}>
        <Form.Item name='id' hidden>
          <Input />
        </Form.Item>
        <Form.Item name='cid' label='cid'>
          <Select
            options={options.map((item) => {
              return {
                label: (
                  <div className='flex justify-between text-black'>
                    {item.label}
                    <div>{item.value}</div>
                  </div>
                ),
                value: item.value,
              };
            })}
          />
        </Form.Item>
        <Form.Item label=' ' colon={false}>
          <Button type='primary' htmlType='submit'>
            Choose
          </Button>
          <Button className='ml-2' htmlType='reset' onClick={onClose}>
            Cancel
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  );
};
