import { useState } from 'react'
import { Search, RefreshCw, Eye, Package, Clock, CheckCircle2, XCircle, Truck } from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'

const statusMap: Record<string, { label: string; color: string; icon: React.ReactNode }> = {
  pending: { label: '待发货', color: 'bg-amber-500/10 text-amber-600 border-amber-200', icon: <Clock className="h-3.5 w-3.5" /> },
  shipped: { label: '已发货', color: 'bg-blue-500/10 text-blue-600 border-blue-200', icon: <Truck className="h-3.5 w-3.5" /> },
  completed: { label: '已完成', color: 'bg-emerald-500/10 text-emerald-600 border-emerald-200', icon: <CheckCircle2 className="h-3.5 w-3.5" /> },
  cancelled: { label: '已取消', color: 'bg-red-500/10 text-red-500 border-red-200', icon: <XCircle className="h-3.5 w-3.5" /> },
}

const mockOrders = [
  { id: 'EX20260401001', userId: 'u1', userName: '张三', itemName: '多肉植物盆栽', itemIcon: '🪴', points: 500, status: 'pending', createdAt: '2026-04-01 10:30', address: '广州市天河区xxx路' },
  { id: 'EX20260402002', userId: 'u2', userName: '李四', itemName: '园艺工具套装', itemIcon: '🔧', points: 800, status: 'shipped', createdAt: '2026-04-02 14:20', address: '深圳市南山区xxx路' },
  { id: 'EX20260403003', userId: 'u3', userName: '王五', itemName: '植物生长灯', itemIcon: '💡', points: 1200, status: 'completed', createdAt: '2026-04-03 09:15', address: '北京市朝阳区xxx路' },
  { id: 'EX20260404004', userId: 'u1', userName: '张三', itemName: '有机肥料包', itemIcon: '🌿', points: 300, status: 'cancelled', createdAt: '2026-04-04 16:45', address: '广州市天河区xxx路' },
  { id: 'EX20260405005', userId: 'u4', userName: '赵六', itemName: '花盆三件套', itemIcon: '🏺', points: 600, status: 'pending', createdAt: '2026-04-05 11:00', address: '上海市浦东新区xxx路' },
  { id: 'EX20260406006', userId: 'u2', userName: '李四', itemName: '种子礼盒', itemIcon: '🌱', points: 200, status: 'completed', createdAt: '2026-04-06 08:30', address: '深圳市南山区xxx路' },
]

export default function ExchangeOrderPage() {
  const [orders] = useState(mockOrders)
  const [statusFilter, setStatusFilter] = useState('all')
  const [search, setSearch] = useState('')
  const [detailOpen, setDetailOpen] = useState(false)
  const [activeOrder, setActiveOrder] = useState<typeof mockOrders[0] | null>(null)

  const filtered = orders.filter(o => {
    if (statusFilter !== 'all' && o.status !== statusFilter) return false
    if (search && !o.userName.includes(search) && !o.id.includes(search)) return false
    return true
  })

  return (
    <div className="space-y-6 animate-fadeIn">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">兑换订单</h1>
        <p className="text-muted-foreground mt-1">查看和管理用户的积分兑换订单，处理发货和售后。</p>
      </div>

      <Card className="border-border/60 shadow-soft">
        <CardHeader className="pb-3 border-b border-border/40">
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <CardTitle className="text-lg flex items-center gap-2">
              <Package className="h-5 w-5 text-primary" /> 订单列表
              <Badge variant="secondary" className="text-xs">{filtered.length}</Badge>
            </CardTitle>
            <div className="flex items-center gap-3">
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="w-[130px] h-9"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  {Object.entries(statusMap).map(([k, v]) => <SelectItem key={k} value={k}>{v.label}</SelectItem>)}
                </SelectContent>
              </Select>
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input placeholder="订单号/用户名..." className="pl-9 w-48 h-9" value={search} onChange={e => setSearch(e.target.value)} />
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHeader className="bg-muted/30">
              <TableRow>
                <TableHead className="pl-6">订单号</TableHead>
                <TableHead>用户</TableHead>
                <TableHead>兑换商品</TableHead>
                <TableHead>消耗积分</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>下单时间</TableHead>
                <TableHead className="w-[60px]" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map(o => {
                const st = statusMap[o.status]
                return (
                  <TableRow key={o.id} className="group hover:bg-muted/20">
                    <TableCell className="pl-6 font-mono text-xs">{o.id}</TableCell>
                    <TableCell className="font-medium">{o.userName}</TableCell>
                    <TableCell>
                      <span className="flex items-center gap-2">
                        <span className="text-lg">{o.itemIcon}</span>{o.itemName}
                      </span>
                    </TableCell>
                    <TableCell><span className="font-mono text-amber-600 font-semibold">{o.points}</span></TableCell>
                    <TableCell>
                      <Badge variant="outline" className={`${st.color} shadow-none gap-1`}>{st.icon}{st.label}</Badge>
                    </TableCell>
                    <TableCell className="text-muted-foreground text-sm">{o.createdAt}</TableCell>
                    <TableCell>
                      <Button variant="ghost" size="icon" className="h-8 w-8 opacity-0 group-hover:opacity-100 text-blue-500"
                        onClick={() => { setActiveOrder(o); setDetailOpen(true) }}>
                        <Eye className="h-4 w-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Dialog open={detailOpen} onOpenChange={setDetailOpen}>
        <DialogContent className="sm:max-w-[450px]">
          <DialogHeader>
            <DialogTitle>订单详情</DialogTitle>
            <DialogDescription>订单号: {activeOrder?.id}</DialogDescription>
          </DialogHeader>
          {activeOrder && (
            <div className="grid gap-3 text-sm p-4 bg-muted/30 rounded-lg border">
              <div className="flex justify-between"><span className="text-muted-foreground">用户</span><span className="font-medium">{activeOrder.userName}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">商品</span><span>{activeOrder.itemIcon} {activeOrder.itemName}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">消耗积分</span><span className="font-mono text-amber-600">{activeOrder.points}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">收货地址</span><span>{activeOrder.address}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">下单时间</span><span>{activeOrder.createdAt}</span></div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
