import { useState, useEffect, useCallback } from 'react'
import { Plus, Search, Trash2, Loader2, MoreHorizontal, Music, Play, Clock } 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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { getRadioProgramList, saveRadioProgram, deleteRadioProgram } from '@/api/radio'
import type { RadioProgram } from '@/api/radio'

const audioStatusMap: Record<number, { label: string; cls: string }> = {
  0: { label: '无音频', cls: 'bg-gray-100 text-gray-600' },
  1: { label: '生成中', cls: 'bg-amber-100 text-amber-700' },
  2: { label: '已就绪', cls: 'bg-green-100 text-green-700' },
}

const formatDuration = (s: number) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`

export default function ProgramPage() {
  const [programs, setPrograms] = useState<RadioProgram[]>([])
  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 [form, setForm] = useState({ title: '', channelId: '1', description: '' })
  const [submitting, setSubmitting] = useState(false)

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

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

  const handleSubmit = async () => {
    if (!form.title) return; setSubmitting(true)
    try { await saveRadioProgram({ ...form, status: 0 } 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"><Music 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={() => { setForm({ title: '', channelId: '1', description: '' }); setDialogOpen(true) }} 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>{programs.map(p => {
                const as = audioStatusMap[p.audioStatus] || audioStatusMap[0]
                return (
                <TableRow key={p.id} className="group hover:bg-muted/30">
                  <TableCell className="pl-6 font-medium">{p.title}</TableCell>
                  <TableCell><Badge variant="secondary" className="text-xs">{p.channelName}</Badge></TableCell>
                  <TableCell><Badge className={as.cls}>{as.label}</Badge></TableCell>
                  <TableCell className="text-muted-foreground flex items-center gap-1"><Clock className="h-3 w-3" />{p.duration ? formatDuration(p.duration) : '-'}</TableCell>
                  <TableCell><div className="flex items-center gap-2 text-xs text-muted-foreground"><span className="flex items-center gap-1"><Play className="h-3 w-3" />{p.playCount}</span><span>❤ {p.likeCount}</span></div></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 deleteRadioProgram(p.id); fetchList() }}><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-[460px]"><DialogHeader><DialogTitle>新增节目</DialogTitle></DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2"><Label>标题 *</Label><Input value={form.title} onChange={e => setForm(f => ({ ...f, title: 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>
          <DialogFooter><Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button><Button onClick={handleSubmit} disabled={submitting || !form.title}>{submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : '保存'}</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
