import { Button, Form, FormInstance, Input, Radio, Table } from "antd";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { debounce } from "lodash";
import { DageTableActions } from "@dage/pc-components";
import { useNavigate } from "react-router-dom";
import { informationApi } from "@/api";
import { TYPE_LIST } from "./constants";

const DEFAULT_PARAMS = {
  pageNum: 1,
  pageSize: 20,
  searchKey: "",
  type: TYPE_LIST[0].value,
};

export default function InformationPage() {
  const navigate = useNavigate();
  const formRef = useRef<FormInstance>(null);
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<[]>([]);
  const [params, setParams] = useState({
    ...DEFAULT_PARAMS,
  });
  const [total, setTotal] = useState(0);

  const getList = useCallback(async () => {
    setLoading(true);
    try {
      const data = await informationApi.getList(params);
      setList(data.records);
      setTotal(data.total);
    } finally {
      setLoading(false);
    }
  }, [params]);

  useEffect(() => {
    getList();
  }, [getList]);

  const handleDelete = useCallback(
    async (id: number) => {
      await informationApi.delete(id);
      getList();
    },
    [getList]
  );

  const COLUMNS = useMemo(() => {
    return [
      {
        title: "标题",
        dataIndex: "name",
      },
      // {
      //   title: "正文",
      //   dataIndex: "richText",
      // },
      {
        title: "发布日期",
        dataIndex: "publishDate",
      },
      {
        title: "操作",
        render: (item: any) => {
          return (
            <DageTableActions
              onEdit={() => navigate(`/information/edit/${item.id}`)}
              onDelete={handleDelete.bind(undefined, item.id)}
            />
          );
        },
      },
    ];
  }, [navigate, handleDelete]);

  const handleReset = useCallback(() => {
    setParams({ ...DEFAULT_PARAMS });
    setTimeout(() => {
      formRef.current?.resetFields();
    });
  }, [formRef]);

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

  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setParams({ ...params, pageNum, pageSize });
    },
    [params]
  );

  return (
    <div className="information">
      <Form
        ref={formRef}
        initialValues={params}
        layout="inline"
        onValuesChange={debounceSearch}
      >
        <Form.Item name="type">
          <Radio.Group>
            {TYPE_LIST.map((item) => (
              <Radio.Button key={item.value} value={item.value}>
                {item.label}
              </Radio.Button>
            ))}
          </Radio.Group>
        </Form.Item>
        <Form.Item label="搜索项" name="searchKey">
          <Input className="w220" placeholder="请输入标题或正文" allowClear />
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            onClick={() => navigate("/information/create")}
          >
            新增
          </Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={handleReset}>重置</Button>
        </Form.Item>
      </Form>

      <Table
        loading={loading}
        className="page-table"
        dataSource={list}
        columns={COLUMNS}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
          position: ["bottomCenter"],
          showSizeChanger: true,
          current: params.pageNum,
          pageSize: params.pageSize,
          total,
          onChange: paginationChange(),
        }}
      />
    </div>
  );
}
