import { useMemo, useState } from 'react';
import { DownloadOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import {
  App as AntdApp,
  Button,
  Card,
  Input,
  Select,
  Table,
  Tag,
} from 'antd';
import type { TableProps } from 'antd';
import AuthButton from '@/components/AuthButton';
import { PERMISSION } from '@/constants/permissions';
import { usePermission } from '@/hooks/usePermission';
import './Orders.scss';

type OrderStatus = 'pending' | 'processing' | 'completed' | 'cancelled';

interface OrderRecord {
  key: string;
  id: string;
  customer: string;
  contact: string;
  amount: number;
  channel: string;
  status: OrderStatus;
  createdAt: string;
}

const statusMeta: Record<OrderStatus, { label: string; color: string }> = {
  pending: { label: '待付款', color: 'orange' },
  processing: { label: '处理中', color: 'processing' },
  completed: { label: '已完成', color: 'success' },
  cancelled: { label: '已取消', color: 'default' },
};

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',
  },
];

export default function Orders() {
  const [orders, setOrders] = useState<OrderRecord[]>(initialOrders);
  const [keyword, setKeyword] = useState('');
  const [status, setStatus] = useState<OrderStatus | 'all'>('all');
  const { message, modal } = AntdApp.useApp();
  const { hasPermission } = usePermission();

  const canEdit = hasPermission(PERMISSION.ORDER_EDIT);

  const filteredOrders = useMemo(() => {
    const normalizedKeyword = keyword.trim().toLowerCase();
    return orders.filter((order) => {
      const matchesKeyword =
        !normalizedKeyword ||
        order.id.toLowerCase().includes(normalizedKeyword) ||
        order.customer.toLowerCase().includes(normalizedKeyword);
      const matchesStatus = status === 'all' || order.status === status;
      return matchesKeyword && matchesStatus;
    });
  }, [orders, keyword, status]);

  const handleProcess = (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('订单状态已更新');
      },
    });
  };

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

  const columns: TableProps<OrderRecord>['columns'] = [
    {
      title: '订单号',
      dataIndex: 'id',
      width: 160,
      render: (value: string) => <code className="order-id">{value}</code>,
    },
    {
      title: '客户',
      dataIndex: 'customer',
      width: 240,
      render: (_value, record) => (
        <div className="order-customer">
          <strong>{record.customer}</strong>
          <span>{record.contact}</span>
        </div>
      ),
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      width: 120,
      align: 'right',
      render: (value: number) => <strong className="order-amount">¥{value.toLocaleString()}</strong>,
    },
    {
      title: '来源渠道',
      dataIndex: 'channel',
      width: 110,
      render: (value: string) => (
        <Tag bordered={false} color="geekblue">
          {value}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (value: OrderStatus) => (
        <Tag color={statusMeta[value].color} bordered={false}>
          {statusMeta[value].label}
        </Tag>
      ),
    },
    { title: '创建时间', dataIndex: 'createdAt', width: 160 },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_value, record) =>
        record.status === 'completed' ? (
          <span className="text-muted">已完成</span>
        ) : canEdit ? (
          <AuthButton
            type="link"
            size="small"
            permission={PERMISSION.ORDER_EDIT}
            onClick={() => handleProcess(record)}
          >
            处理
          </AuthButton>
        ) : (
          <span className="text-muted">-</span>
        ),
    },
  ];

  return (
    <div className="orders-page">
      <div className="page-header">
        <div>
          <h1 className="page-header__title">订单管理</h1>
          <p className="page-header__desc">
            跟踪销售订单的处理进度；导出与处理操作分别受独立权限码控制。
          </p>
        </div>
        <div className="page-header__actions">
          <Button
            icon={<ReloadOutlined />}
            onClick={() => message.success('订单数据已刷新')}
          >
            刷新
          </Button>
          <AuthButton
            type="primary"
            icon={<DownloadOutlined />}
            permission={PERMISSION.ORDER_EXPORT}
            onClick={handleExport}
          >
            导出订单
          </AuthButton>
        </div>
      </div>

      <Card className="filter-card" variant="borderless">
        <div className="page-toolbar">
          <Input
            allowClear
            prefix={<SearchOutlined />}
            placeholder="搜索订单号 / 客户名称"
            value={keyword}
            onChange={(event) => setKeyword(event.target.value)}
            style={{ width: 280 }}
          />
          <Select<OrderStatus | 'all'>
            value={status}
            onChange={setStatus}
            style={{ width: 150 }}
            options={[
              { value: 'all', label: '全部状态' },
              { value: 'pending', label: '待付款' },
              { value: 'processing', label: '处理中' },
              { value: 'completed', label: '已完成' },
              { value: 'cancelled', label: '已取消' },
            ]}
          />
          <span className="text-muted">
            共 {filteredOrders.length} 条订单 · 合计 ¥
            {filteredOrders.reduce((sum, order) => sum + order.amount, 0).toLocaleString()}
          </span>
        </div>
      </Card>

      <Card className="table-card" variant="borderless">
        <Table<OrderRecord>
          rowKey="key"
          columns={columns}
          dataSource={filteredOrders}
          scroll={{ x: 1000 }}
          pagination={{
            pageSize: 8,
            showSizeChanger: false,
            showTotal: (total) => `共 ${total} 条`,
          }}
        />
      </Card>
    </div>
  );
}
