import { useState, useEffect, useCallback } from 'react'
import { Search, Loader2, Users, Calendar, CreditCard } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { getSubscriptionList } from '@/api/radio'
import type { RadioSubscription } from '@/api/radio'

const statusMap: Record<number, { label: string; cls: string }> = {
  1: { label: '生效中', cls: 'bg-green-500/10 text-green-700 border-green-500/20' },
  2: { label: '已过期', cls: 'bg-gray-100 text-gray-600' },
  0: { label: '待支付', cls: 'bg-amber-100 text-amber-700' },
}

const planMap: Record<string, string> = { monthly: '月订阅', quarterly: '季订阅', annual: '年订阅' }

export default function SubscriptionPage() {
  const [subs, setSubs] = useState<RadioSubscription[]>([])
  const [loading, setLoading] = useState(true)
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')

  const fetchList = useCallback(async () => {
    setLoading(true)
    try {
      const params: any = { current: page, pageSize: 10, keyword: search || undefined }
      if (statusFilter !== 'all') params.status = parseInt(statusFilter)
      const res = await getSubscriptionList(params)
      if (res?.data) { setSubs(res.data.list || []); setTotal(res.data.total || 0) }
    } catch (e) { console.error(e) } finally { setLoading(false) }
  }, [page, search, statusFilter])

  useEffect(() => { fetchList() }, [fetchList])

  const totalPages = Math.ceil(total / 10)

  return (
    <div className="space-y-6 animate-fadeIn">
      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card className="border-l-4 border-l-green-500 shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">活跃订阅</CardTitle><Users className="h-4 w-4 text-green-500" /></CardHeader>
          <CardContent><div className="text-2xl font-bold">{subs.filter(s => s.status === 1).length}</div></CardContent>
        </Card>
        <Card className="border-l-4 border-l-amber-500 shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">总收入</CardTitle><CreditCard className="h-4 w-4 text-amber-500" /></CardHeader>
          <CardContent><div className="text-2xl font-bold">¥{subs.reduce((s, sub) => s + sub.amount, 0).toFixed(1)}</div></CardContent>
        </Card>
        <Card className="border-l-4 border-l-blue-500 shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">总订阅数</CardTitle><Calendar className="h-4 w-4 text-blue-500" /></CardHeader>
          <CardContent><div className="text-2xl font-bold">{total}</div></CardContent>
        </Card>
      </div>

      <Card className="border-border/60 shadow-sm">
        <CardHeader className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pb-6">
          <div className="space-y-1">
            <CardTitle className="text-xl flex items-center gap-2"><CreditCard className="h-5 w-5 text-primary" />订阅管理</CardTitle>
            <CardDescription>查看频道订阅记录</CardDescription>
          </div>
          <div className="flex items-center gap-3">
            <Select value={statusFilter} onValueChange={v => { setStatusFilter(v); setPage(1) }}>
              <SelectTrigger className="w-[120px] h-10"><SelectValue placeholder="状态" /></SelectTrigger>
              <SelectContent><SelectItem value="all">全部</SelectItem><SelectItem value="1">生效中</SelectItem><SelectItem value="2">已过期</SelectItem></SelectContent>
            </Select>
          </div>
        </CardHeader>
        <CardContent>
          {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><TableHead className="font-semibold">状态</TableHead>
              </TableRow></TableHeader>
              <TableBody>{subs.map(s => {
                const st = statusMap[s.status] || statusMap[0]
                return (
                <TableRow key={s.id} className="hover:bg-muted/30">
                  <TableCell className="pl-6 font-medium">{s.userName}</TableCell>
                  <TableCell><Badge variant="secondary">{s.channelName}</Badge></TableCell>
                  <TableCell className="text-sm">{planMap[s.planType] || s.planType}</TableCell>
                  <TableCell className="font-mono text-amber-600">¥{s.amount}</TableCell>
                  <TableCell className="text-xs text-muted-foreground">{new Date(s.startAt).toLocaleDateString()} ~ {new Date(s.expireAt).toLocaleDateString()}</TableCell>
                  <TableCell><Badge className={st.cls}>{st.label}</Badge></TableCell>
                </TableRow>
              )})}</TableBody></Table>
            </div>
          )}
          {totalPages > 1 && <div className="flex items-center justify-between pt-4"><p className="text-sm text-muted-foreground">共 {total} 条</p><div className="flex gap-2"><Button variant="outline" size="sm" disabled={page<=1} onClick={()=>setPage(p=>p-1)}>上一页</Button><Button variant="outline" size="sm" disabled={page>=totalPages} onClick={()=>setPage(p=>p+1)}>下一页</Button></div></div>}
        </CardContent>
      </Card>
    </div>
  )
}
