import { FC, useEffect, useMemo, useRef, useState } from "react";
import { Form, Input, Modal, ModalProps, Table } from "antd";
import style from "@/components/AddIndexModal/index.module.scss";
import { getReportAssessListApi } from "@/api";
import { debounce } from "lodash";
import { IManageIndexDetail } from "@/types";
import { ASSESSMENT_TYPE_OPTIONS, PUBLISH_STATUS_MAP } from "@/constants";
import useApp from "antd/es/app/useApp";

export interface ChooseFormModalProps extends Omit<ModalProps, "onOk"> {
  onCancel?: () => void;
  onOk?: (id: number) => void;
}

export const ChooseFormModal: FC<ChooseFormModalProps> = ({
  open,
  onOk,
  onCancel,
  ...rest
}) => {
  const { message } = useApp();
  const [submitLoading, setSubmitLoading] = useState(false);
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState({
    searchKey: "",
  });
  const [list, setList] = useState<IManageIndexDetail[]>([]);
  const checkedId = useRef<null | number>(null);

  const handleCancel = () => {
    onCancel?.();
  };

  const handleConfirm = async () => {
    if (!checkedId.current) {
      message.warning("请选择考核单");
      return;
    }

    try {
      setSubmitLoading(true);
      onOk?.(checkedId.current);
    } finally {
      setSubmitLoading(false);
    }
  };

  const getList = async () => {
    try {
      setLoading(true);
      const data = await getReportAssessListApi(params.searchKey);
      setList(data);
    } finally {
      setLoading(false);
    }
  };

  const debounceSearch = useMemo(
    () =>
      debounce((changedVal: unknown, vals: any) => {
        setParams({ ...params, ...vals });
      }, 500),
    [params]
  );

  useEffect(() => {
    if (!open) return;
    getList();
  }, [open, params]);

  return (
    <Modal
      className={style.modal}
      title="请选择考核单"
      okText="提交"
      cancelText="取消"
      open={open}
      width={1000}
      okButtonProps={{
        disabled: submitLoading,
      }}
      forceRender
      maskClosable={false}
      onOk={handleConfirm}
      onCancel={handleCancel}
      {...rest}
    >
      <Form
        layout="inline"
        style={{ marginBottom: 20 }}
        onValuesChange={debounceSearch}
      >
        <Form.Item label="搜索" name="searchKey">
          <Input placeholder="请输入考核标题" className="w220" allowClear />
        </Form.Item>
      </Form>

      <Table
        loading={loading}
        dataSource={list}
        rowKey="id"
        rowSelection={{
          type: "radio",
          onChange(selectedRowKeys) {
            checkedId.current = selectedRowKeys[0] as number;
          },
        }}
        pagination={false}
        columns={[
          {
            title: "名称",
            dataIndex: "name",
            align: "center",
          },
          {
            title: "类别",
            align: "center",
            minWidth: 100,
            render: (item: IManageIndexDetail) => {
              return ASSESSMENT_TYPE_OPTIONS.find((i) => i.value === item.type)
                ?.label;
            },
          },
          {
            title: "说明",
            dataIndex: "remark",
            align: "center",
            minWidth: 100,
            ellipsis: true,
          },
          {
            title: "考核周期",
            align: "center",
            minWidth: 100,
            render: (item: IManageIndexDetail) => {
              return `${item.dateStart}-${item.dateEnd}`;
            },
          },
          {
            title: "发布状态",
            align: "center",
            minWidth: 100,
            render: (item: IManageIndexDetail) => {
              return (
                <p style={{ color: PUBLISH_STATUS_MAP[item.status].color }}>
                  {PUBLISH_STATUS_MAP[item.status].label}
                </p>
              );
            },
          },
        ]}
      />
    </Modal>
  );
};
