import { useState, useEffect } from 'react'
import { Plus, Trash2, Loader2, FolderTree } 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 { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { getRadioCategoryList, saveRadioCategory, deleteRadioCategory } from '@/api/radio'
import type { RadioCategory } from '@/api/radio'

export default function RadioCategoryPage() {
  const [categories, setCategories] = useState<RadioCategory[]>([])
  const [loading, setLoading] = useState(true)
  const [dialogOpen, setDialogOpen] = useState(false)
  const [form, setForm] = useState({ name: '', sort: 0 })
  const [submitting, setSubmitting] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [toDelete, setToDelete] = useState<RadioCategory | null>(null)

  const fetchList = async () => {
    setLoading(true)
    try { const res = await getRadioCategoryList(); if (res?.data) setCategories(res.data) }
    catch (e) { console.error(e) } finally { setLoading(false) }
  }

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

  const handleSubmit = async () => {
    if (!form.name) return; setSubmitting(true)
    try { await saveRadioCategory({ ...form, status: 1 }); 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-row items-center justify-between pb-6">
          <div className="space-y-1">
            <CardTitle className="text-xl flex items-center gap-2"><FolderTree className="h-5 w-5 text-primary" />频道分类 <Badge variant="secondary" className="text-xs">{categories.length}</Badge></CardTitle>
            <CardDescription>管理电台频道分类</CardDescription>
          </div>
          <Button onClick={() => { setForm({ name: '', sort: 0 }); setDialogOpen(true) }} className="h-10 gap-2"><Plus className="h-4 w-4" />新增</Button>
        </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="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
              {categories.map(c => (
                <div key={c.id} className="flex items-center justify-between p-4 rounded-xl border border-border/50 hover:border-primary/30 hover:bg-primary/5 transition-all group">
                  <div className="flex items-center gap-3">
                    <div className="h-10 w-10 rounded-lg bg-purple-500/10 flex items-center justify-center"><FolderTree className="h-5 w-5 text-purple-500" /></div>
                    <div><p className="font-medium text-sm">{c.name}</p><p className="text-xs text-muted-foreground">排序: {c.sort}</p></div>
                  </div>
                  <Button variant="ghost" size="icon" className="h-8 w-8 opacity-0 group-hover:opacity-100 text-destructive" onClick={() => { setToDelete(c); setDeleteOpen(true) }}><Trash2 className="h-4 w-4" /></Button>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-[400px]"><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 type="number" value={form.sort} onChange={e => setForm(f => ({ ...f, sort: parseInt(e.target.value) || 0 }))} /></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 deleteRadioCategory(toDelete.id); setDeleteOpen(false); fetchList() } }}>删除</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
