import {
  useState,
  useEffect,
  useMemo,
  forwardRef,
  useImperativeHandle,
  useRef,
} from "react";
import { Alert, Button, Col, Form, Input, message, Row } from "antd";
import LangInput from "@/components/LangInput";
import type { TableItemType, ColumnRelation, ColumnItem } from "@/type";
import { EditableProTable, ProColumns } from "@ant-design/pro-components";
import { DATA_TYPE_OPTIONS } from "@/constants";
import {
  validateColumnCode,
  validateAliasName,
  validateTableCode,
} from "@/utils/validator";
import LoadingDot from "@/components/LoadingDot";
import { useModel } from "umi";

const columns: ProColumns<ColumnItem>[] = [
  {
    title: "字段名称",
    dataIndex: "langNameList",
    width: 120,
    renderFormItem: () => {
      return <LangInput />;
    },
  },
  {
    title: "字段编码",
    dataIndex: "schemaName",
    valueType: "text",
    width: 140,
    formItemProps: {
      rules: [
        { required: true, message: "请输入字段编码" },
        validateColumnCode,
      ],
    },
  },
  {
    title: "字段类型",
    dataIndex: "type",
    valueType: "select",
    fieldProps: {
      options: DATA_TYPE_OPTIONS,
    },
    formItemProps: {
      rules: [{ required: true, message: "请选择字段类型" }],
    },
  },
];

const TableItem = forwardRef(
  (
    {
      data,
      onChange,
    }: {
      data: TableItemType;
      onChange: (data: TableItemType) => void;
    },
    ref
  ) => {
    const [form] = Form.useForm();
    const [tableForm] = Form.useForm();
    const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(
      data?.tableColumnList.map((item) => item.id)
    );
    const [selectedRowKeys, setSelectedKeys] = useState<React.Key[]>(
      data?.tableColumnList.map((item) => item.id)
    );
    const [selectedRows, setSelectedRows] = useState<ColumnItem[]>(
      data?.tableColumnList || []
    );
    const [dataSource, setDataSource] = useState<readonly ColumnItem[]>(
      data?.tableColumnList || []
    );

    useImperativeHandle(ref, () => ({
      // 校验表单与可编辑表格
      validate: async () => {
        await form.validateFields();
        await tableForm.validateFields(
          selectedRowKeys
            .map((key) => [
              [key, "schemaName"],
              [key, "type"],
            ])
            .flat(1)
        );
      },
    }));

    const change = (tableColumnList: ColumnItem[]) => {
      const values = form.getFieldsValue();
      onChange({
        isTable: true,
        table: {
          ...data?.table,
          ...values,
        },
        tableColumnList,
      });
    };

    useEffect(() => {
      change(selectedRows);
    }, [selectedRows]);

    return (
      <div className="rounded-12px overflow-hidden bg-white">
        <div
          className="w-full h-10px mb-4px"
          style={{ background: data?.table?.style?.color || "#0076fc" }}
        ></div>
        <div className="px-12px mb-4px">
          {
            data?.table?.langNameList?.find((item) => item.name === "zh-CN")
              ?.value
          }
        </div>
        <Form className="px-12px" form={form} initialValues={data?.table}>
          <Row gutter={8}>
            <Col span={12}>
              <Form.Item
                name="schemaName"
                label="表名"
                rules={[
                  { required: true, message: "请输入表名" },
                  validateTableCode,
                ]}
              >
                <Input placeholder="请输入" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="aliasName"
                label="别名"
                rules={[
                  { required: true, message: "请输入别名" },
                  validateAliasName,
                ]}
              >
                <Input placeholder="请输入" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <EditableProTable
          columns={columns}
          value={dataSource}
          onChange={setDataSource}
          pagination={false}
          recordCreatorProps={false}
          rowKey={"id"}
          tableAlertRender={false}
          rowSelection={{
            type: "checkbox",
            selectedRowKeys,
            onChange: (keys, selectedRows) => {
              setSelectedKeys(keys);
              setSelectedRows(selectedRows);
            },
            alwaysShowAlert: false,
          }}
          editable={{
            form: tableForm,
            type: "multiple",
            editableKeys,
            onValuesChange: (_, recordList) => {
              change(
                recordList.filter((item) => selectedRowKeys.includes(item.id))
              );
              setDataSource(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
      </div>
    );
  }
);

export default function AITable(props: {
  content: string;
  onChange?: (data: any) => void;
  onTry?: () => void;
}) {
  // AI生成数据
  const [data, setData] = useState<{
    tables: TableItemType[];
    relations: ColumnRelation[];
  }>();
  const { onCreateByAi } = useModel("erModel");

  // 记录已选数据
  const [selectedData, setSelectedData] = useState<TableItemType[]>([]);

  // 操作状态
  const [status, setStatus] = useState<"done" | "try" | "abort">();

  // 可编辑表格ref
  const tableRef = useRef<Record<string, { validate: () => Promise<void> }>>(
    {}
  );

  function regexExtractJSON(markdown: string) {
    const jsonRegex = /```(?:json)?\n([\s\S]*?)\n```/g;
    const matches = [];
    let match;

    while ((match = jsonRegex.exec(markdown)) !== null) {
      try {
        const jsonObj = JSON.parse(match[1]);
        matches.push(jsonObj);
      } catch (e) {
        console.warn("无效JSON:", match[0]);
      }
    }
    return matches;
  }

  const handleParseJsonByMd = (str: string) => {
    // 根据markdown格式取出json部分数据
    const md = str;
    let json: unknown;
    if (md.includes("```json")) {
      json = regexExtractJSON(props.content)?.[0];
      console.log("解析结果：", json);
      return json;
    }

    return undefined;
  };

  useEffect(() => {
    const data = handleParseJsonByMd(props.content);
    setData(data as any);
    setTimeout(() => {}, 300);
  }, [props.content]);

  useEffect(() => {
    // 改成自动添加到页面
    if (data?.tables?.length) {
      onCreateByAi(data);
    }
  }, [data]);

  const handleChange = (data: TableItemType) => {
    if (selectedData.find((item) => item.table.id === data.table.id)) {
    }
    setSelectedData((prev) => {
      const index = prev.findIndex((item) => item.table.id === data.table.id);
      if (index > -1) {
        return prev.map((item, i) => {
          if (i === index) return data;
          return item;
        });
      }

      return [...prev, data];
    });
  };

  const canOk = useMemo(() => {
    let can = false;
    selectedData.forEach((item) => {
      if (item.tableColumnList.length) can = true;
    });
    return can;
  }, [selectedData]);

  // const handleSubmit = (status: "done" | "try" | "abort") => {
  //   switch (status) {
  //     case "done":
  //       // 校验数据
  //       const result = selectedData.filter(
  //         (item) => item.tableColumnList.length
  //       );
  //       Promise.all(
  //         result.map((item) => tableRef.current[item.table.id].validate())
  //       )
  //         .then(() => {
  //           // 勾选后 过滤失效的关联关系
  //           const relations = (data?.relations || []).filter((relation) => {
  //             return !!result.find((tableItem) =>
  //               tableItem.tableColumnList.find(
  //                 (columnItem) =>
  //                   columnItem.id === relation.primaryKey ||
  //                   columnItem.id === relation.foreignKey
  //               )
  //             );
  //           });
  //           onCreateByAi({
  //             relations,
  //             tables: result,
  //           });
  //           setStatus("done");
  //           props.onChange?.(result);
  //         })
  //         .catch((err) => {
  //           message.warning("请检查数据");
  //           console.log("校验失败：", err);
  //         });
  //       break;
  //     case "try":
  //       setStatus("try");
  //       props.onTry?.();
  //       break;
  //     case "abort":
  //       setStatus("abort");
  //       break;
  //   }
  // };

  return (
    <div>
      {/* {data ? (
        <>
          <div className="mb-12px text-#333 font-bold">
            以为你生成以下内容：
          </div>
          <div className="flex flex-col gap-12px">
            {data?.tables?.map((item) => {
              return (
                <TableItem
                  key={item.table.id}
                  ref={(ref) =>
                    ref && (tableRef.current[item.table.id] = ref as any)
                  }
                  data={item}
                  onChange={handleChange}
                />
              );
            })}
          </div>
          {!status && (
            <div className="flex gap-12px mt-12px">
              <Button disabled={!canOk} onClick={() => handleSubmit("done")}>
                确认
              </Button>
              <Button onClick={() => handleSubmit("try")}>再试一次</Button>
              <Button onClick={() => handleSubmit("abort")}>放弃</Button>
            </div>
          )}
          {status === "done" && (
            <Alert
              className="mt-12px"
              message="已确认生成"
              type="success"
              showIcon
            />
          )}
          {status === "abort" && (
            <Alert className="mt-12px" message="已放弃该方案" type="error" />
          )}
        </>
      ) : ( */}
      {!data && (
        <div className="flex">
          {/\<generate>[\s\S]*?<\/generate>/.test(props.content) ? (
            <span>易码工坊智能助手.</span>
          ) : (
            <>
              <LoadingDot />
              思考完成，正在生成数据...
            </>
          )}
        </div>
      )}
      {data && (
        <Alert
          className="mt-12px"
          message="已完成生成"
          type="success"
          showIcon
        />
      )}
      {/* )} */}
    </div>
  );
}
