import { useEffect, useState } from "react"
import { Link } from "react-router-dom"
import {
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  FileTextOutlined,
  ShoppingCartOutlined,
} from "@ant-design/icons"
import { Button, Card, Empty, Space, Spin, Table, Tag, Typography } from "antd"
import { toast } from "../utils/toast"
import { listOrders, type Order } from "../api/orders"

const { Title, Text, Paragraph } = Typography

const ORDER_STATUS = {
  pending: { label: "待支付", color: "warning", icon: <ClockCircleOutlined /> },
  paid: { label: "已支付", color: "success", icon: <CheckCircleOutlined /> },
  cancelled: { label: "已取消", color: "default", icon: <CloseCircleOutlined /> },
  refunded: { label: "已退款", color: "purple", icon: <ExclamationCircleOutlined /> },
} as const

function fmtDate(s: string) {
  return new Date(s).toLocaleString("zh-CN", { hour12: false })
}

export default function Orders() {
  const [orders, setOrders] = useState<Order[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    listOrders()
      .then((res) => setOrders(res.data.data ?? []))
      .catch(() => toast.error("订单列表加载失败"))
      .finally(() => setLoading(false))
  }, [])

  if (loading) {
    return (
      <div style={{ height: 420, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <Spin size="large" tip="正在加载订单" />
      </div>
    )
  }

  return (
    <Space direction="vertical" size={24} style={{ width: "100%" }}>
      <div>
        <Title level={3} style={{ margin: 0 }}>订单管理</Title>
        <Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>
          查看购买、续费和退款相关订单。
        </Paragraph>
      </div>

      <Card
        title={<Space><FileTextOutlined /> 全部订单</Space>}
        bordered
        extra={
          <Link to="/store">
            <Button type="primary" icon={<ShoppingCartOutlined />}>购买服务</Button>
          </Link>
        }
      >
        {orders.length === 0 ? (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="暂无订单记录"
          >
            <Link to="/store">
              <Button type="primary">去商店选购</Button>
            </Link>
          </Empty>
        ) : (
          <Table
            rowKey="id"
            dataSource={orders}
            pagination={{ pageSize: 10, showSizeChanger: false }}
            columns={[
              {
                title: "订单号",
                dataIndex: "out_order_no",
                render: (value: string, record: Order) => (
                  <Link to={`/orders/${record.id}`}>
                    <Text code>{value}</Text>
                  </Link>
                ),
              },
              {
                title: "状态",
                dataIndex: "status",
                render: (value: Order["status"]) => {
                  const meta = ORDER_STATUS[value] ?? ORDER_STATUS.paid
                  return <Tag color={meta.color} icon={meta.icon}>{meta.label}</Tag>
                },
              },
              {
                title: "应付金额",
                key: "paid",
                align: "right" as const,
                render: (_: unknown, record: Order) => {
                  const paid = ((record.total_amount - record.discount_amount) / 100).toFixed(2)
                  return <Text strong>¥{paid}</Text>
                },
              },
              {
                title: "创建时间",
                dataIndex: "created_at",
                render: (value: string) => <Text type="secondary">{fmtDate(value)}</Text>,
              },
              {
                title: "操作",
                key: "action",
                align: "right" as const,
                render: (_: unknown, record: Order) => (
                  <Link to={`/orders/${record.id}`}>
                    <Button size="small">查看详情</Button>
                  </Link>
                ),
              },
            ]}
          />
        )}
      </Card>
    </Space>
  )
}
