import { useState, useEffect, useCallback } from 'react'
import { Plus, Search, Trash2, Loader2, MoreHorizontal, Hash, Pencil } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { getExchangeItemList, saveExchangeItem, deleteExchangeItem, getExchangeOrderList } from '@/api/plant'
import type { ExchangeItem, ExchangeOrder } from '@/api/plant'

export default function ExchangePage() {
  const [items, setItems] = useState<ExchangeItem[]>([])
  const [orders, setOrders] = useState<ExchangeOrder[]>([])
  const [loading, setLoading] = useState(true)
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const [tab, setTab] = useState('items')
  const [dialogOpen, setDialogOpen] = useState(false)
  const [form, setForm] = useState({ name: '', description: '', points: 100, stock: 10, sort: 0 })
  const [submitting, setSubmitting] = useState(false)

  const fetchItems = useCallback(async () => {
    setLoading(true)
    try { const res = await getExchangeItemList({ current: page, pageSize: 10, keyword: search || undefined }); if (res?.data) { setItems(res.data.list || []); setTotal(res.data.total || 0) } }
    catch (e) { console.error(e) } finally { setLoading(false) }
  }, [page, search])

  const fetchOrders = useCallback(async () => {
    setLoading(true)
    try { const res = await getExchangeOrderList({ current: page, pageSize: 10 }); if (res?.data) { setOrders(res.data.list || []); setTotal(res.data.total || 0) } }
    catch (e) { console.error(e) } finally { setLoading(false) }
  }, [page])

  useEffect(() => { if (tab === 'items') fetchItems(); else fetchOrders() }, [tab, fetchItems, fetchOrders])

  const handleSubmit = async () => {
    if (!form.name) return; setSubmitting(true)
    try { await saveExchangeItem({ ...form, status: 1 }); setDialogOpen(false); fetchItems() }
    catch (e) { console.error(e) } finally { setSubmitting(false) }
  }

  const statusMap: Record<number, string> = { 0: '待处理', 1: '已完成', 2: '已过期' }

  return (
    <div className="space-y-6 animate-fadeIn">
      <Card className="border-border/60 shadow-sm">
        <CardHeader className="pb-4">
          <CardTitle className="text-xl flex items-center gap-2"><Hash className="h-5 w-5 text-primary" />积分兑换</CardTitle>
          <CardDescription>管理兑换商品和兑换订单</CardDescription>
        </CardHeader>
        <CardContent>
          <Tabs value={tab} onValueChange={v => { setTab(v); setPage(1) }}>
            <div className="flex items-center justify-between mb-4">
              <TabsList><TabsTrigger value="items">商品管理</TabsTrigger><TabsTrigger value="orders">兑换订单</TabsTrigger></TabsList>
              {tab === 'items' && <Button onClick={() => { setForm({ name: '', description: '', points: 100, stock: 10, sort: 0 }); setDialogOpen(true) }} className="h-9 gap-2"><Plus className="h-4 w-4" />新增商品</Button>}
            </div>
            <TabsContent value="items">
              {loading ? <div className="flex items-center justify-center py-16"><Loader2 className="h-8 w-8 animate-spin text-primary" /></div> : (
                <div className="rounded-lg border border-border/50 overflow-hidden">
                  <Table><TableHeader className="bg-muted/50"><TableRow className="hover:bg-transparent">
                    <TableHead className="font-semibold pl-6">商品</TableHead><TableHead className="font-semibold">积分</TableHead>
                    <TableHead className="font-semibold">库存</TableHead><TableHead className="font-semibold">状态</TableHead><TableHead className="w-[60px]" />
                  </TableRow></TableHeader>
                  <TableBody>{items.map(item => (
                    <TableRow key={item.id} className="hover:bg-muted/30">
                      <TableCell className="pl-6"><div className="flex items-center gap-3">{item.cover && <img src={item.cover} alt="" className="h-10 w-10 rounded-lg object-cover border" />}<div><p className="font-medium text-sm">{item.name}</p><p className="text-xs text-muted-foreground">{item.description}</p></div></div></TableCell>
                      <TableCell className="font-mono font-semibold text-amber-600">{item.points}</TableCell>
                      <TableCell><Badge variant="secondary">{item.stock}</Badge></TableCell>
                      <TableCell>{item.status === 1 ? <Badge className="bg-green-500/10 text-green-700">上架</Badge> : <Badge variant="secondary">下架</Badge>}</TableCell>
                      <TableCell><DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
                        <DropdownMenuContent align="end"><DropdownMenuItem className="text-destructive" onClick={async () => { await deleteExchangeItem(item.id); fetchItems() }}><Trash2 className="mr-2 h-4 w-4" />删除</DropdownMenuItem></DropdownMenuContent>
                      </DropdownMenu></TableCell>
                    </TableRow>
                  ))}</TableBody></Table>
                </div>
              )}
            </TabsContent>
            <TabsContent value="orders">
              {loading ? <div className="flex items-center justify-center py-16"><Loader2 className="h-8 w-8 animate-spin text-primary" /></div> : (
                <div className="rounded-lg border border-border/50 overflow-hidden">
                  <Table><TableHeader className="bg-muted/50"><TableRow className="hover:bg-transparent">
                    <TableHead className="font-semibold pl-6">商品</TableHead><TableHead className="font-semibold">用户</TableHead>
                    <TableHead className="font-semibold">积分</TableHead><TableHead className="font-semibold">状态</TableHead><TableHead className="font-semibold">时间</TableHead>
                  </TableRow></TableHeader>
                  <TableBody>{orders.map(o => (
                    <TableRow key={o.id} className="hover:bg-muted/30">
                      <TableCell className="pl-6 font-medium">{o.itemName}</TableCell>
                      <TableCell>{o.userName}</TableCell>
                      <TableCell className="font-mono text-amber-600">{o.points}</TableCell>
                      <TableCell><Badge variant="secondary">{statusMap[o.status] || '未知'}</Badge></TableCell>
                      <TableCell className="text-xs text-muted-foreground">{new Date(o.createdAt).toLocaleDateString()}</TableCell>
                    </TableRow>
                  ))}</TableBody></Table>
                </div>
              )}
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-[460px]"><DialogHeader><DialogTitle>新增兑换商品</DialogTitle></DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2"><Label>名称 *</Label><Input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} /></div>
            <div className="grid gap-2"><Label>描述</Label><Input value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} /></div>
            <div className="grid grid-cols-2 gap-4">
              <div className="grid gap-2"><Label>积分</Label><Input type="number" value={form.points} onChange={e => setForm(f => ({ ...f, points: parseInt(e.target.value) || 0 }))} /></div>
              <div className="grid gap-2"><Label>库存</Label><Input type="number" value={form.stock} onChange={e => setForm(f => ({ ...f, stock: parseInt(e.target.value) || 0 }))} /></div>
            </div>
          </div>
          <DialogFooter><Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button><Button onClick={handleSubmit} disabled={submitting || !form.name}>{submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : '保存'}</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
