import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import type { MenuProps, TabsProps } from 'antd';
import { Button, Dropdown, Space, 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 ProdDetail from '@/pages/prod/list/detail';
import {
  createProd,
  getProdDetail,
  getProdPage,
  type Prod,
  type ProdReq,
  updateProd,
} from '@/services/prod/prod-manager';
import { baseTenantColumns } from './config';

const ProdList = () => {
  const tableRef = useRef<ActionType>(null);
  const [type, setType] = useState<'create' | 'update' | 'test'>('create');
  const [status, setStatus] = useState<number>();
  const detailRef = useRef<ConfigurableDrawerFormRef>(null);
  const navigator = useNavigate();
  // const editRef = useRef<ConfigurableDrawerFormRef>(null);
  const [id, setId] = useState<number>(0);
  const onChange = useCallback(
    (key: string) => {
      setStatus(Number(key));
    },
    [status],
  );

  const onFetch = async (params: ProdReq) => {
    const data = await getProdPage({
      ...params,
      status: status ? status : undefined,
    });
    return {
      data: data.list,
      success: true,
    };
  };

  const handleAdd = () => {
    setType('create');
    detailRef.current?.open({});
  };

  const toolbarActions: ToolbarAction[] = [
    {
      key: 'add',
      label: '新建',
      type: 'primary',
      icon: <PlusOutlined />,
      onClick: handleAdd,
    },
  ];
  const handleEdit = async (row: Prod) => {
    setType('update');
    const res = await getProdDetail({ id: row.prodId as number });
    setId(row.prodId as number);
    detailRef.current?.open(res);
  };
  // 商品更新
  // const _handleEditSubmit = async (values: Prod) => {
  //   await updateProd(values);
  //   tableRef.current?.reload();
  //   message.success("编辑成功");
  //   return true;
  // };
  const handleSubmit = useCallback(
    async (values: Prod) => {
      if (type === 'create') {
        await createProd(values);
      } else {
        await updateProd({
          ...values,
          categoryId: id,
        });
      }
      tableRef.current?.reload();
      return true;
    },

    [id, type],
  );

  const handleLink = (key: string, row: Prod) => {
    if (key === 'sku') {
      // navigator(`/prod/list/sku/${row.prodId}`);
    }
    console.log(key, row);
  };
  // const renderDetailFooter = () => {
  //   if (type === "update") {
  //     return (
  //       <Space>
  //         <Button onClick={() => detailRef.current?.close()}>取消</Button>
  //         <Button type="primary" onClick={handleEditSubmit}>
  //           确定
  //         </Button>
  //       </Space>
  //     );
  //   } else {
  //     return (
  //       <Button type="primary" onClick={() => detailRef.current?.close()}>
  //         确定
  //       </Button>
  //     );
  //   }
  // };
  const itemsMenu = (row: Prod): MenuProps['items'] => [
    {
      key: 'edit',
      label: (
        <Button type="link" onClick={() => handleEdit(row)}>
          商品编辑
        </Button>
      ),
    },
    {
      key: 'sku',
      label: (
        <Button type="link" onClick={() => handleLink('sku', row)}>
          SKU管理
        </Button>
      ),
    },
    {
      key: 'rules-service',
      label: <Button type="link">服务规则编辑</Button>,
    },
    {
      key: 'extend-service',
      label: <Button type="link">扩展服务管理</Button>,
    },
    {
      key: 'status',
      label: <Button type="link">状态控制</Button>,
    },
    {
      key: 'delete',
      label: (
        <Button color="danger" variant="link">
          删除商品
        </Button>
      ),
    },
  ];
  const actionColumns: ProColumns<Prod> = {
    title: '操作',
    dataIndex: 'option',
    valueType: 'option',
    fixed: 'right',
    align: 'center',

    width: 200,
    render: (_text: React.ReactNode, record: Prod, _: number) => [
      <Space style={{ width: '100%' }} wrap size={0} key={record.prodId}>
        <Space.Compact direction="vertical" block key="1">
          <Button type="link" onClick={() => handleEdit(record)}>
            商品编辑
          </Button>
          <Button type="link" onClick={() => handleLink('sku', record)}>
            SKU管理
          </Button>
        </Space.Compact>
        <Space.Compact direction="vertical" block key="2">
          <Button type="link">服务规则</Button>
          <Button type="link">扩展服务</Button>
        </Space.Compact>
        <Space.Compact direction="vertical" block key="3">
          <Dropdown menu={{ items: itemsMenu(record) }} placement="bottomLeft">
            <Button type="link">
              <EllipsisOutlined />
            </Button>
          </Dropdown>
        </Space.Compact>
      </Space>,
    ],
  };

  const columns = [...baseTenantColumns, actionColumns];
  const renderChildren = () => {
    return (
      <>
        <EnhancedProTable<Prod>
          ref={tableRef}
          columns={columns}
          request={onFetch}
          toolbarActions={toolbarActions}
          headerTitle="短信渠道"
          showIndex={false}
          rowKey="prodId"
          showSelection={false}
        />

        <ConfigurableDrawerForm
          ref={detailRef}
          onSubmit={handleSubmit}
          // footer={renderDetailFooter()}
          title={formStatusType[type]}
          width={'80vw'}
          bodyStyle={{
            background: '#f5f5f5',
            paddingTop: 8,
          }}
        >
          <ProdDetail />
        </ConfigurableDrawerForm>
        {/* <ConfigurableDrawerForm
          ref={editRef}
          onSubmit={handleEditSubmit}
          footer={renderDetailFooter()}
          width={"80vw"}
          bodyStyle={{
            background: "#f5f5f5",
            paddingTop: 8,
          }}
        >
          <ProdDetail />
        </ConfigurableDrawerForm> */}
      </>
    );
  };

  const items: TabsProps['items'] = [
    {
      key: '',
      label: '全部商品',
      children: renderChildren(),
    },
    {
      key: '1',
      label: '出售中的商品',
      children: renderChildren(),
    },
    {
      key: '0',
      label: '仓库中的商品',
      children: renderChildren(),
    },
    {
      key: '2',
      label: '待审核的商品',
      children: renderChildren(),
    },
  ];
  return (
    <Tabs
      defaultActiveKey={status as unknown as string}
      items={items}
      onChange={onChange}
    />
  );
};

export default ProdList;
