import { fetchInitialCredentials, fetchProductList, fetchUpdateProduct } from '@/services/product';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { useIntl, useLocation, useNavigate } from '@umijs/max';
import { Button, Popconfirm, Tag, message } from 'antd';
import { useRef, useState } from 'react';
import { ProductForm } from './components/Form';
import { CredentialModal } from './Detail/components/CredentialModal';

interface LocationState {
  page?: number;
  pageSize?: number;
}

export default function ProductPage() {
  const intl = useIntl();
  const navigate = useNavigate();
  const location = useLocation();
  const state = (location.state ?? {}) as LocationState;
  const actionRef = useRef<ActionType>();
  const [credData, setCredData] = useState<API.FetchInitialCredentialsResp | null>(null);
  const [credOpen, setCredOpen] = useState(false);
  const [pagination, setPagination] = useState({
    current: state.page ?? 1,
    pageSize: state.pageSize ?? 20,
  });

  const handleCreateSuccess = async (ticket?: string) => {
    actionRef.current?.reload();
    if (!ticket) return;
    const res = await fetchInitialCredentials({ ticket });
    setCredData(res.data ?? null);
    setCredOpen(true);
  };

  const handleToggleStatus = async (record: API.ProductItem) => {
    const res = await fetchUpdateProduct({
      id: record.id,
      name: record.name,
      status: record.status === 1 ? 0 : 1,
    });
    if (!res.success) return;
    message.success('操作成功');
    actionRef.current?.reload();
  };

  const columns: ProColumns<API.ProductItem>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 160,
      render: (_, r) => (
        <a
          onClick={() =>
            navigate(`/admin/products/${r.id}`, {
              state: { page: pagination.current, pageSize: pagination.pageSize },
            })
          }
        >
          {r.name}
        </a>
      ),
    },
    { title: 'Code', dataIndex: 'code', width: 160, copyable: true },
    { title: 'App Key', dataIndex: 'appKey', width: 300, copyable: true },
    { title: '备注', dataIndex: 'remark' },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (_, r) => (
        <Tag color={r.status === 1 ? 'success' : 'default'}>{r.status === 1 ? '启用' : '禁用'}</Tag>
      ),
    },
    { title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', width: 180 },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      render: (_, r) => [
        <ProductForm
          key="edit"
          mode="edit"
          initialValues={r}
          onSuccess={() => actionRef.current?.reload()}
          trigger={<a>编辑</a>}
        />,
        <Popconfirm
          key="status"
          title={r.status === 1 ? `确认禁用「${r.name}」？` : `确认启用「${r.name}」？`}
          onConfirm={() => handleToggleStatus(r)}
        >
          <a>{r.status === 1 ? '禁用' : '启用'}</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer title={intl.formatMessage({ id: 'admin.product.title' })}>
      <ProTable<API.ProductItem>
        actionRef={actionRef}
        columns={columns}
        rowKey="id"
        search={false}
        request={fetchProductList}
        scroll={{ x: 900 }}
        tableLayout="fixed"
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          defaultPageSize: 20,
          pageSizeOptions: [10, 20, 50, 100],
          showSizeChanger: true,
          onChange: (page, pageSize) => setPagination({ current: page, pageSize }),
        }}
        toolBarRender={() => [
          <ProductForm
            key="create"
            mode="add"
            onSuccess={handleCreateSuccess}
            trigger={
              <Button type="primary">{intl.formatMessage({ id: 'admin.product.create' })}</Button>
            }
          />,
        ]}
      />
      <CredentialModal open={credOpen} data={credData} onClose={() => setCredOpen(false)} />
    </PageContainer>
  );
}
