import { Button, Input, message, Modal, Table, Tooltip } from 'antd';
import { Fragment, useEffect, useMemo, useState } from 'react';
import { usePromptStore } from '../store/prompt';
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,
  CaretRightOutlined,
  PlusOutlined,
  ExportOutlined,
} from '@ant-design/icons';
import clsx from 'clsx';
import { TextArea } from '@/pages/container/components/TextArea';

import { marked } from 'marked';
import { extractKeysFromBraces } from '@/utils/extra';
import { useAiStore } from '@/pages/ai-chat';
import { CardBlank } from '@/components/card/CardBlank';
import { isObjectNull } from '@/utils/is-null';

const FormModal = () => {
  const [form] = Form.useForm();
  const promptStore = usePromptStore(
    useShallow((state) => {
      return {
        showEdit: state.showEdit,
        setShowEdit: state.setShowEdit,
        formData: state.formData,
        updateData: state.updateData,
        runAi: state.runAi,
      };
    }),
  );
  useEffect(() => {
    const open = promptStore.showEdit;
    if (open) {
      if (isObjectNull(promptStore.formData)) {
        form.setFieldsValue({});
      } else {
        form.setFieldsValue(promptStore.formData || {});
      }
    }
  }, [promptStore.showEdit, promptStore.formData]);
  const onFinish = async (values: any) => {
    let other = {};
    if (!values.id) {
      other = {
        presetData: {
          validator: {},
          data: {
            prompt: '',
            inputs: [],
          },
        },
      };
    }
    promptStore.updateData({
      ...values,
      ...other,
    });
  };
  const onClose = () => {
    promptStore.setShowEdit(false);
    form.resetFields();
  };
  const isEdit = promptStore.formData.id;
  return (
    <Modal
      title={isEdit ? 'Edit' : 'Add'}
      open={promptStore.showEdit}
      onClose={() => promptStore.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='key' label='key'>
          <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 = useNewNavigate();
  const aiStore = useAiStore(
    useShallow((state) => {
      return {
        open: state.open,
        setOpen: state.setOpen,
        key: state.key,
        setKey: state.setKey,
      };
    }),
  );
  const promptStore = usePromptStore(
    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,
        runAi: state.runAi,
      };
    }),
  );
  const [codeEdit, setCodeEdit] = useState(false);
  const [code, setCode] = useState('');
  const [form] = Form.useForm<{ inputs: any[] }>();
  useEffect(() => {
    promptStore.getList();
  }, []);
  useEffect(() => {
    if (!codeEdit) {
      form.setFieldsValue({ inputs: [] });
    }
  }, [codeEdit]);
  const onAdd = () => {
    promptStore.setFormData({});
    promptStore.setShowEdit(true);
    setCodeEdit(false);
  };
  const getFormInputs = () => {
    if (!codeEdit) return;
    console.log('blur getFormInputs');

    const keys = extractKeysFromBraces(code);
    const inputs = form.getFieldValue('inputs') || [];
    const newInputs = keys
      .map((key) => {
        const has = inputs.some((item: any) => item.key === key);
        if (!has) {
          return {
            key,
            value: '',
          };
        }
        return null;
      })
      .filter(Boolean);
    if (newInputs.length > 0) {
      form.setFieldsValue({ inputs: [...inputs, ...newInputs] });
    }
  };
  const len = form.getFieldValue('inputs')?.length || 0;
  return (
    <div className='w-full h-full flex flex-col'>
      <div className='flex flex-grow overflow-hidden h-full'>
        <div className='p-2 bg-white'>
          <Button onClick={onAdd} icon={<PlusOutlined />}></Button>
        </div>
        <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'>
            {promptStore.list.length > 0 &&
              promptStore.list.map((item) => {
                const { presetData } = item;
                const md = presetData?.data?.prompt || '';
                const inputs = presetData?.data?.inputs || [];
                const html = marked.parse(md);
                return (
                  <Fragment key={item.id}>
                    <div className='flex text-sm gap flex-col w-[600px] max-h-[400px] bg-white p-4 rounded-lg' key={item.id} onClick={() => {}}>
                      <div
                        className='px-4 cursor-pointer'
                        onClick={() => {
                          setCode(md);
                          promptStore.setFormData(item);
                          form.setFieldsValue({
                            inputs: inputs.map((item) => {
                              return { key: item.key, value: item.value };
                            }),
                          });
                          setCodeEdit(true);
                        }}>
                        <div
                          className='font-bold flex'
                          onClick={(e) => {
                            // copy(item.code);
                            // e.stopPropagation();
                            // message.success('copy code success');
                          }}>
                          {item.title || '-'}
                          <div
                            className=' ml-3 text-xs text-gray-400'
                            style={{
                              fontFamily: 'D-DIN',
                            }}>
                            {item?.key ? item.key : '-'}
                          </div>
                        </div>
                        <div className='font-light 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='px-4 mt-2'>{md ? 'Prompt' : ''}</div>
                      <div className='px-4'>
                        <div className='max-h-52 overflow-scroll scrollbar p-4 border shadow-sm mt-1'>
                          <div dangerouslySetInnerHTML={{ __html: html }}></div>
                        </div>
                      </div>
                      <div className='flex mt-4 ml-4'>
                        <Button.Group>
                          <Button
                            onClick={(e) => {
                              promptStore.setFormData(item);
                              promptStore.setShowEdit(true);
                              setCodeEdit(false);
                              e.stopPropagation();
                            }}
                            icon={<EditOutlined />}></Button>
                          <Button
                            onClick={(e) => {
                              e.stopPropagation();
                              Modal.confirm({
                                title: 'Delete',
                                content: 'Are you sure delete this data?',
                                onOk: () => {
                                  promptStore.deleteData(item.id);
                                },
                              });
                              e.stopPropagation();
                            }}
                            icon={<DeleteOutlined />}></Button>
                          <Button
                            icon={<CaretRightOutlined />}
                            onClick={() => {
                              // aiStore.setKey(location.pathname);
                              // aiStore.setOpen(true);
                              message.error('Not implemented');
                            }}
                          />
                          <Tooltip title='Export Config'>
                            <Button
                              icon={<ExportOutlined />}
                              onClick={() => {
                                message.error('Not implemented');
                              }}
                            />
                          </Tooltip>
                        </Button.Group>
                      </div>
                    </div>
                  </Fragment>
                );
              })}
            <CardBlank className='w-[600px]' />
            {promptStore.list.length == 0 && (
              <div className='text-center' key={'no-data'}>
                No Data
              </div>
            )}
          </div>
        </div>
        <div className={clsx('bg-gray-100 border-l flex flex-col 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'>
              <Button
                onClick={() => {
                  setCodeEdit(false);
                  promptStore.setFormData({});
                }}
                icon={<LeftOutlined />}></Button>
              <Button
                onClick={() => {
                  // console.log('save', promptStore.formData);
                  const { presetData } = promptStore.formData;
                  const inputs = form.getFieldValue('inputs') || [];
                  promptStore.updateData({ ...promptStore.formData, presetData: { ...presetData, data: { ...presetData.data, prompt: code, inputs } } });
                }}
                icon={<SaveOutlined />}></Button>
            </div>
          </div>
          <div className='flex-grow p-2 rounded-2 shadow-sm overflow-hidden'>
            <TextArea
              value={code}
              language='markdown'
              placeholder='Please enter markdown code.'
              onChange={(value) => {
                setCode(value);
              }}
              onBlur={() => {
                console.log('blur');
                setTimeout(() => {
                  getFormInputs();
                }, 400);
              }}
              className='h-full max-h-full scrollbar'
              style={{
                overflow: 'auto',
                minHeight: '200px',
                //  height: '100%', // height: '100%' 有bug
              }}
            />
          </div>
          <div className='flex-shrink-0 px-4 mt-4'>
            <h1 className={clsx('mb-2', len === 0 && 'hidden')}>Match Keys</h1>
            <Form form={form}>
              <Form.List name='inputs'>
                {(fields, { add, remove }) => {
                  return (
                    <>
                      {fields.map((field, index) => {
                        return (
                          <div key={field.name + '-' + index} className='flex gap-2'>
                            <Form.Item name={[field.name, 'key']} rules={[{ required: true, message: 'Missing name' }]}>
                              <Input placeholder='name' />
                            </Form.Item>
                            <Form.Item name={[field.name, 'value']} rules={[{ required: true, message: 'Missing value' }]}>
                              <Input placeholder='value' />
                            </Form.Item>
                            {/* <Button onClick={() => add()} className='flex items-center'>
                              +
                            </Button> */}
                            <Button onClick={() => remove(field.name)}>-</Button>
                          </div>
                        );
                      })}
                    </>
                  );
                }}
              </Form.List>
            </Form>
          </div>
        </div>
      </div>
      <FormModal />
    </div>
  );
};
