import { useState, useEffect, useCallback } from 'react'
import { Plus, Search, Pencil, Trash2, Loader2, MoreHorizontal, Radio } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Switch } from '@/components/ui/switch'
import { getRadioChannelList, saveRadioChannel, updateRadioChannel, deleteRadioChannel, getRadioCategoryList } from '@/api/radio'
import type { RadioChannel, RadioCategory } from '@/api/radio'

export default function ChannelPage() {
  const [channels, setChannels] = useState<RadioChannel[]>([])
  const [categories, setCategories] = useState<RadioCategory[]>([])
  const [loading, setLoading] = useState(true)
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const [dialogOpen, setDialogOpen] = useState(false)
  const [isEdit, setIsEdit] = useState(false)
  const [form, setForm] = useState({ id: '', categoryId: '', name: '', description: '', isFree: true, isVipOnly: false, monthlyPrice: 0, sort: 0 })
  const [submitting, setSubmitting] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [toDelete, setToDelete] = useState<RadioChannel | null>(null)

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

  useEffect(() => { fetchList() }, [fetchList])
  useEffect(() => { getRadioCategoryList().then(res => { if (res?.data) setCategories(res.data) }) }, [])

  const handleAdd = () => { setIsEdit(false); setForm({ id: '', categoryId: categories[0]?.id || '', name: '', description: '', isFree: true, isVipOnly: false, monthlyPrice: 0, sort: 0 }); setDialogOpen(true) }
  const handleEdit = (c: RadioChannel) => { setIsEdit(true); setForm({ id: c.id, categoryId: c.categoryId, name: c.name, description: c.description || '', isFree: c.isFree, isVipOnly: c.isVipOnly, monthlyPrice: c.monthlyPrice || 0, sort: c.sort }); setDialogOpen(true) }

  const handleSubmit = async () => {
    if (!form.name || !form.categoryId) return; setSubmitting(true)
    try { if (isEdit) await updateRadioChannel({ ...form, status: 1 } as any); else await saveRadioChannel({ ...form, status: 1 } as any); setDialogOpen(false); fetchList() }
    catch (e) { console.error(e) } finally { setSubmitting(false) }
  }

  return (
    <div className="space-y-6 animate-fadeIn">
      <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"><Radio className="h-5 w-5 text-primary" />频道管理 <Badge variant="secondary" className="text-xs">{total}</Badge></CardTitle>
            <CardDescription>管理电台频道及定价</CardDescription>
          </div>
          <div className="flex items-center gap-3">
            <div className="relative"><Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input placeholder="搜索..." className="pl-9 w-[180px] h-10 bg-muted/30" value={search} onChange={e => { setSearch(e.target.value); setPage(1) }} /></div>
            <Button onClick={handleAdd} className="h-10 gap-2"><Plus className="h-4 w-4" />新增</Button>
          </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="w-[60px]" />
              </TableRow></TableHeader>
              <TableBody>{channels.map(c => (
                <TableRow key={c.id} className="group hover:bg-muted/30">
                  <TableCell className="pl-6">{c.cover ? <img src={c.cover} alt="" className="h-10 w-10 rounded-lg object-cover border" /> : <div className="h-10 w-10 rounded-lg bg-muted/50" />}</TableCell>
                  <TableCell><div><p className="font-medium text-sm">{c.name}</p><p className="text-xs text-muted-foreground">{c.description}</p></div></TableCell>
                  <TableCell><Badge variant="secondary">{c.categoryName}</Badge></TableCell>
                  <TableCell>{c.isFree ? <Badge className="bg-green-500/10 text-green-700">免费</Badge> : <span className="text-sm font-mono text-amber-600">¥{c.monthlyPrice}/月</span>}</TableCell>
                  <TableCell>{c.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 onClick={() => handleEdit(c)}><Pencil className="mr-2 h-4 w-4" />编辑</DropdownMenuItem>
                        <DropdownMenuItem className="text-destructive" onClick={() => { setToDelete(c); setDeleteOpen(true) }}><Trash2 className="mr-2 h-4 w-4" />删除</DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}</TableBody></Table>
            </div>
          )}
        </CardContent>
      </Card>

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-[500px]"><DialogHeader><DialogTitle>{isEdit ? '编辑频道' : '新增频道'}</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><Select value={form.categoryId} onValueChange={v => setForm(f => ({ ...f, categoryId: v }))}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent>{categories.map(c => <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>)}</SelectContent></Select></div>
              <div className="grid gap-2"><Label>排序</Label><Input type="number" value={form.sort} onChange={e => setForm(f => ({ ...f, sort: parseInt(e.target.value) || 0 }))} /></div>
            </div>
            <div className="flex items-center gap-6">
              <div className="flex items-center gap-2"><Switch checked={form.isFree} onCheckedChange={v => setForm(f => ({ ...f, isFree: v }))} /><Label>免费</Label></div>
              {!form.isFree && <div className="grid gap-2 flex-1"><Label>月价(¥)</Label><Input type="number" value={form.monthlyPrice} onChange={e => setForm(f => ({ ...f, monthlyPrice: parseFloat(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>

      <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
        <DialogContent><DialogHeader><DialogTitle>确认删除频道「{toDelete?.name}」？</DialogTitle></DialogHeader>
          <DialogFooter><Button variant="outline" onClick={() => setDeleteOpen(false)}>取消</Button><Button variant="destructive" onClick={async () => { if (toDelete) { await deleteRadioChannel(toDelete.id); setDeleteOpen(false); fetchList() } }}>删除</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
