import { useCallback, useMemo, useState } from 'react';
import { DownloadOutlined } from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import { App as AntdApp, Button } from 'antd';
import { createOrderColumns } from './columns';
import type { OrderRecord, OrderStatus } from './types';
import './Orders.scss';

interface OrderQuery {
  id?: string;
  customer?: string;
  status?: OrderStatus;
  orders: OrderRecord[];
}

const initialOrders: OrderRecord[] = [
  {
    key: '1',
    id: 'SO20261017001',
    customer: '杭州云启科技有限公司',
    contact: '林女士',
    amount: 28600,
    channel: '官网',
    status: 'completed',
    createdAt: '2026-10-17 09:42',
  },
  {
    key: '2',
    id: 'SO20261017002',
    customer: '上海灵犀网络科技',
    contact: '周先生',
    amount: 15800,
    channel: '销售转介',
    status: 'processing',
    createdAt: '2026-10-17 08:36',
  },
  {
    key: '3',
    id: 'SO20261016008',
    customer: '深圳前海智造有限公司',
    contact: '苏女士',
    amount: 63200,
    channel: '线下活动',
    status: 'pending',
    createdAt: '2026-10-16 18:20',
  },
  {
    key: '4',
    id: 'SO20261016005',
    customer: '北京星辰数据服务',
    contact: '何先生',
    amount: 9600,
    channel: '官网',
    status: 'cancelled',
    createdAt: '2026-10-16 15:08',
  },
  {
    key: '5',
    id: 'SO20261015012',
    customer: '成都锦江数字科技',
    contact: '杨女士',
    amount: 41200,
    channel: '销售转介',
    status: 'completed',
    createdAt: '2026-10-15 11:36',
  },
  {
    key: '6',
    id: 'SO20261015003',
    customer: '南京云帆软件有限公司',
    contact: '王先生',
    amount: 22800,
    channel: '官网',
    status: 'processing',
    createdAt: '2026-10-15 09:15',
  },
  {
    key: '7',
    id: 'SO20261014009',
    customer: '武汉光谷智能科技',
    contact: '赵女士',
    amount: 36700,
    channel: '线下活动',
    status: 'pending',
    createdAt: '2026-10-14 16:50',
  },
  {
    key: '8',
    id: 'SO20261014002',
    customer: '西安丝路信息技术',
    contact: '陈先生',
    amount: 12400,
    channel: '官网',
    status: 'completed',
    createdAt: '2026-10-14 10:22',
  },
  {
    key: '9',
    id: 'SO20261013006',
    customer: '广州珠江互联科技',
    contact: '黄女士',
    amount: 51800,
    channel: '销售转介',
    status: 'processing',
    createdAt: '2026-10-13 14:06',
  },
  {
    key: '10',
    id: 'SO20261012004',
    customer: '厦门海峡电子商务',
    contact: '吴先生',
    amount: 18900,
    channel: '官网',
    status: 'completed',
    createdAt: '2026-10-12 11:44',
  },
];

const Orders = () => {
  const [orders, setOrders] = useState<OrderRecord[]>(initialOrders);
  const [summary, setSummary] = useState(() => ({
    count: initialOrders.length,
    amount: initialOrders.reduce((sum, order) => sum + order.amount, 0),
  }));
  const { message, modal } = AntdApp.useApp();

  const tableParams = useMemo(() => ({ orders }), [orders]);

  const handleProcess = useCallback(
    (record: OrderRecord) => {
      modal.confirm({
        title: '处理订单',
        content: `确定将订单「${record.id}」标记为已完成吗？`,
        okText: '标记完成',
        cancelText: '取消',
        onOk: () => {
          setOrders((prev) =>
            prev.map((order) =>
              order.key === record.key ? { ...order, status: 'completed' } : order,
            ),
          );
          message.success('订单状态已更新');
        },
      });
    },
    [message, modal],
  );

  const columns = useMemo(
    () => createOrderColumns({ onProcess: handleProcess }),
    [handleProcess],
  );

  const handleExport = () => {
    message.success(`已导出 ${summary.count} 条订单记录（演示）`);
  };

  return (
    <div className="orders-page">
      <div className="page-header">
        <div>
          <h1 className="page-header__title">订单管理</h1>
          <p className="page-header__desc">
            跟踪销售订单的处理进度，支持筛选与导出。
          </p>
        </div>
      </div>

      <ProTable<OrderRecord, OrderQuery>
        rowKey="key"
        columns={columns}
        params={tableParams}
        cardProps={{ className: 'orders-table-card' }}
        search={{ labelWidth: 'auto', defaultCollapsed: false }}
        scroll={{ x: 1000 }}
        options={false}
        pagination={{
          defaultPageSize: 8,
          showSizeChanger: true,
          hideOnSinglePage: false,
          showTotal: (total) => `共 ${total} 条`,
        }}
        toolBarRender={() => [
          <span key="summary" className="text-muted">
            共 {summary.count} 条订单 · 合计 ¥{summary.amount.toLocaleString()}
          </span>,
          <Button key="export" type="primary" icon={<DownloadOutlined />} onClick={handleExport}>
            导出订单
          </Button>,
        ]}
        request={async (params) => {
          const { current = 1, pageSize = 8, id, customer, status, orders: dataSource } =
            params;
          const normalizedId = id?.trim().toLowerCase();
          const normalizedCustomer = customer?.trim().toLowerCase();

          const filteredOrders = dataSource.filter((order) => {
            const matchesId =
              !normalizedId || order.id.toLowerCase().includes(normalizedId);
            const matchesCustomer =
              !normalizedCustomer ||
              order.customer.toLowerCase().includes(normalizedCustomer);
            const matchesStatus = !status || order.status === status;
            return matchesId && matchesCustomer && matchesStatus;
          });

          setSummary({
            count: filteredOrders.length,
            amount: filteredOrders.reduce((sum, order) => sum + order.amount, 0),
          });

          const start = (current - 1) * pageSize;
          return {
            data: filteredOrders.slice(start, start + pageSize),
            total: filteredOrders.length,
            success: true,
          };
        }}
      />
    </div>
  );
};

export default Orders;
