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

const ALL_CATEGORY_TYPE = [
  {
    label: "全部",
    value: "",
  },
  ...CATEGORY_TYPE,
];

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

export default function CollectionPage() {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const formRef = useRef<FormInstance>(null);
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<[]>([]);
  const [params, setParams] = useState({
    ...DEFAULT_PARAMS,
    searchKey: searchParams.get("searchKey") || "",
    dictType: searchParams.get("dictType") || ALL_CATEGORY_TYPE[0].value,
  });
  const [total, setTotal] = useState(0);

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

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

  const COLUMNS = useMemo(() => {
    return [
      {
        title: "标题",
        dataIndex: "name",
      },
      {
        title: "年代",
        dataIndex: "dictAge",
      },
      {
        title: "级别",
        dataIndex: "dictLevel",
      },
      {
        title: "来源",
        dataIndex: "dictSource",
      },
      // {
      //   title: "封面",
      //   render: (item: any) => {
      //     return (
      //       <Image
      //         height={60}
      //         src={`${process.env.REACT_APP_API_URL}${process.env.REACT_APP_IMG_PUBLIC}${item.thumb}`}
      //       />
      //     );
      //   },
      // },
      {
        title: "简介",
        width: 250,
        render: (item: any) => {
          return <p className="limit-line line-2">{item.description}</p>;
        },
      },
      {
        title: "发布日期",
        dataIndex: "publishDate",
      },
      {
        title: "操作",
        render: (item: any) => {
          return (
            <DageTableActions
              onEdit={() => navigate(`/collection/edit/${item.id}`)}
              onDelete={handleDelete.bind(undefined, item.id)}
            />
          );
        },
      },
    ];
  }, [navigate, handleDelete]);

  useEffect(() => {
    setSearchParams({
      searchKey: params.searchKey,
      dictType: params.dictType,
    });
  }, [params.searchKey, params.dictType, setSearchParams]);

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

  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}
        layout="inline"
        initialValues={params}
        onValuesChange={debounceSearch}
      >
        <Form.Item label="搜索项" name="searchKey">
          <Input placeholder="请输入" maxLength={10} showCount allowClear />
        </Form.Item>
        <Form.Item label="类别" name="dictType">
          <Select style={{ width: 220 }} options={ALL_CATEGORY_TYPE} />
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={() => navigate("/collection/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>
  );
}
