import { fetchInitialCredentials, fetchProductList, fetchUpdateProduct } from '@/services/product';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { useIntl, 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';

export default function ProductPage() {
  const intl = useIntl();
  const navigate = useNavigate();
  const actionRef = useRef<ActionType>();
  const [credData, setCredData] = useState<API.FetchInitialCredentialsResp | null>(null);
  const [credOpen, setCredOpen] = useState(false);

  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) => {
    await fetchUpdateProduct({
      id: record.id,
      name: record.name,
      status: record.status === 1 ? 0 : 1,
    });
    message.success('操作成功');
    actionRef.current?.reload();
  };

  const columns: ProColumns<API.ProductItem>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      render: (_, r) => <a onClick={() => navigate(`/admin/products/${r.id}`)}>{r.name}</a>,
    },
    { title: 'Code', dataIndex: 'code', copyable: true },
    { title: 'App Key', dataIndex: 'appKey', copyable: true },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, r) => (
        <Tag color={r.status === 1 ? 'success' : 'default'}>{r.status === 1 ? '启用' : '禁用'}</Tag>
      ),
    },
    { title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime' },
    {
      title: '操作',
      valueType: 'option',
      render: (_, r) => [
        <ProductForm
          key="edit"
          mode="edit"
          initialValues={r}
          onSuccess={() => actionRef.current?.reload()}
          trigger={<a>编辑</a>}
        />,
        <Popconfirm
          key="status"
          title={r.status === 1 ? '确认禁用？' : '确认启用？'}
          onConfirm={() => handleToggleStatus(r)}
        >
          <a className={r.status === 1 ? 'text-red-500' : ''}>{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}
        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>
  );
}
