import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import type { TabsProps } from 'antd';
import { Tabs } from 'antd';
import { useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
  type ConfigurableDrawerFormRef,
} from '@/components/DrawerForm';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import { formStatusType } from '@/constants';
import {
  type Category,
  type CategoryReq,
  createProdCategory,
  getProdCategoryPage,
  updateProdCategory,
} from '@/services/prod/category-manager';
import { baseTenantColumns, formColumns } from './config';

const ProdCategory = () => {
  const tableRef = useRef<ActionType>(null);
  const [type, setType] = useState<'create' | 'update' | 'test'>('create');
  const [grade, setGrade] = useState<number>();
  const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
  const [id, setId] = useState<number>(0);
  const onChange = useCallback(
    (key: string) => {
      setGrade(Number(key));
    },
    [grade],
  );

  const onFetch = async (params: CategoryReq) => {
    const data = await getProdCategoryPage({
      ...params,
      grade: grade ? Number(grade) : undefined,
    });
    return {
      data: data,
      success: true,
    };
  };

  const handleAdd = () => {
    setType('create');
    configurableDrawerRef.current?.open({ grade: 1 });
  };

  const toolbarActions: ToolbarAction[] = [
    {
      key: 'add',
      label: '新建',
      type: 'primary',
      icon: <PlusOutlined />,
      onClick: handleAdd,
    },
  ];
  const handleEdit = async (row: Category) => {
    setType('update');
    row.categoryId && setId(row.categoryId);
    configurableDrawerRef.current?.open(row);
  };
  const handleSubmit = useCallback(
    async (values: Category) => {
      if (type === 'create') {
        await createProdCategory(values);
      } else {
        await updateProdCategory({
          ...values,
          categoryId: id,
        });
      }
      tableRef.current?.reload(true);
      return true;
    },

    [id, type],
  );

  const actionColumns: ProColumns<Category> = {
    title: '操作',
    dataIndex: 'option',
    valueType: 'option',
    fixed: 'right',
    width: 120,
    render: (_text: React.ReactNode, record: Category, _: number) => [
      <a key="edit" onClick={() => handleEdit(record)}>
        编辑
      </a>,
      <a key="detail">详情</a>,
    ],
  };

  const columns = [...baseTenantColumns, actionColumns];
  const renderChildren = () => {
    return (
      <>
        <EnhancedProTable<Category>
          ref={tableRef}
          columns={columns}
          rowKey="categoryId"
          request={onFetch}
          toolbarActions={toolbarActions}
          headerTitle="短信渠道"
          showIndex={false}
          showSelection={false}
        />
        <ConfigurableDrawerForm
          ref={configurableDrawerRef}
          title={formStatusType[type]}
          width={'60vw'}
          columns={formColumns({ type })}
          onSubmit={handleSubmit}
          footer={undefined}
          bodyStyle={{}}
        />
      </>
    );
  };

  const items: TabsProps['items'] = [
    {
      key: '',
      label: '全部分类',
      children: renderChildren(),
    },
    {
      key: '3',
      label: '三级分类',
      children: renderChildren(),
    },
    {
      key: '2',
      label: '二级分类',
      children: renderChildren(),
    },
    {
      key: '1',
      label: '一级分类',
      children: renderChildren(),
    },
  ];
  return (
    <Tabs
      defaultActiveKey={grade as unknown as string}
      items={items}
      destroyOnHidden
      onChange={onChange}
    />
  );
};

export default ProdCategory;
