import { useState, useEffect, useCallback } from 'react'
import { Plus, Search, Pencil, Trash2, Loader2, MoreHorizontal, Book, Eye, EyeOff } 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, DialogDescription, 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 { Textarea } from '@/components/ui/textarea'
import { getWikiList, saveWiki, updateWiki, deleteWiki, getWikiClassList } from '@/api/plant'
import type { PlantWiki, PlantWikiClass } from '@/api/plant'

export default function WikiPage() {
  const [wikis, setWikis] = useState<PlantWiki[]>([])
  const [classes, setClasses] = useState<PlantWikiClass[]>([])
  const [loading, setLoading] = useState(true)
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const [classFilter, setClassFilter] = useState('all')
  const [dialogOpen, setDialogOpen] = useState(false)
  const [isEdit, setIsEdit] = useState(false)
  const [form, setForm] = useState({ id: '', title: '', classId: '', content: '', cover: '', status: 1 })
  const [submitting, setSubmitting] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [toDelete, setToDelete] = useState<PlantWiki | null>(null)

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

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

  const handleAdd = () => { setIsEdit(false); setForm({ id: '', title: '', classId: classes[0]?.id || '', content: '', cover: '', status: 1 }); setDialogOpen(true) }
  const handleEdit = (w: PlantWiki) => { setIsEdit(true); setForm({ id: w.id, title: w.title, classId: w.classId, content: w.content, cover: w.cover || '', status: w.status }); setDialogOpen(true) }

  const handleSubmit = async () => {
    if (!form.title || !form.classId) return; setSubmitting(true)
    try { if (isEdit) await updateWiki(form); else await saveWiki(form); setDialogOpen(false); fetchList() }
    catch (e) { console.error(e) } finally { setSubmitting(false) }
  }

  const handleDelete = async () => {
    if (!toDelete) return
    try { await deleteWiki(toDelete.id); setDeleteOpen(false); fetchList() } catch (e) { console.error(e) }
  }

  const totalPages = Math.ceil(total / 10)

  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"><Book 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 w-full sm:w-auto flex-wrap">
            <div className="relative flex-1 sm:flex-none"><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-full sm:w-[180px] h-10 bg-muted/30" value={search} onChange={e => { setSearch(e.target.value); setPage(1) }} /></div>
            <Select value={classFilter} onValueChange={v => { setClassFilter(v); setPage(1) }}>
              <SelectTrigger className="w-[130px] h-10"><SelectValue placeholder="分类" /></SelectTrigger>
              <SelectContent><SelectItem value="all">全部分类</SelectItem>{classes.map(c => <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>)}</SelectContent>
            </Select>
            <Button onClick={handleAdd} className="h-10 gap-2 shadow-sm"><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="w-[60px]" />
              </TableRow></TableHeader>
              <TableBody>
                {wikis.length === 0 ? <TableRow><TableCell colSpan={5} className="h-32 text-center text-muted-foreground">暂无数据</TableCell></TableRow>
                : wikis.map(w => (
                  <TableRow key={w.id} className="group hover:bg-muted/30">
                    <TableCell className="pl-6">{w.cover ? <img src={w.cover} alt="" className="h-10 w-16 rounded-lg object-cover border" /> : <div className="h-10 w-16 rounded-lg bg-muted/50 flex items-center justify-center"><Book className="h-4 w-4 text-muted-foreground/40" /></div>}</TableCell>
                    <TableCell className="font-medium">{w.title}</TableCell>
                    <TableCell><Badge variant="secondary">{w.className}</Badge></TableCell>
                    <TableCell>{w.status === 1 ? <Badge className="bg-green-500/10 text-green-700 border-green-500/20"><Eye className="h-3 w-3 mr-1" />已发布</Badge> : <Badge variant="secondary"><EyeOff className="h-3 w-3 mr-1" />草稿</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(w)}><Pencil className="mr-2 h-4 w-4" />编辑</DropdownMenuItem>
                          <DropdownMenuItem className="text-destructive" onClick={() => { setToDelete(w); setDeleteOpen(true) }}><Trash2 className="mr-2 h-4 w-4" />删除</DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </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><span className="text-sm text-muted-foreground px-2">{page}/{totalPages}</span><Button variant="outline" size="sm" disabled={page>=totalPages} onClick={()=>setPage(p=>p+1)}>下一页</Button></div></div>}
        </CardContent>
      </Card>

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-[560px]"><DialogHeader><DialogTitle>{isEdit ? '编辑百科' : '新增百科'}</DialogTitle><DialogDescription>编辑植物百科词条内容</DialogDescription></DialogHeader>
          <div className="grid gap-4 py-4 max-h-[60vh] overflow-y-auto pr-1">
            <div className="grid gap-2"><Label>标题 *</Label><Input value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} /></div>
            <div className="grid grid-cols-2 gap-4">
              <div className="grid gap-2"><Label>分类 *</Label><Select value={form.classId} onValueChange={v => setForm(f => ({ ...f, classId: v }))}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent>{classes.map(c => <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>)}</SelectContent></Select></div>
              <div className="grid gap-2"><Label>状态</Label><Select value={String(form.status)} onValueChange={v => setForm(f => ({ ...f, status: parseInt(v) }))}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent><SelectItem value="1">已发布</SelectItem><SelectItem value="0">草稿</SelectItem></SelectContent></Select></div>
            </div>
            <div className="grid gap-2"><Label>封面URL</Label><Input value={form.cover} onChange={e => setForm(f => ({ ...f, cover: e.target.value }))} placeholder="图片地址" /></div>
            <div className="grid gap-2"><Label>内容</Label><Textarea value={form.content} onChange={e => setForm(f => ({ ...f, content: e.target.value }))} rows={6} /></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>

      <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
        <DialogContent><DialogHeader><DialogTitle>确认删除</DialogTitle><DialogDescription>确定要删除「{toDelete?.title}」吗？</DialogDescription></DialogHeader>
          <DialogFooter><Button variant="outline" onClick={()=>setDeleteOpen(false)}>取消</Button><Button variant="destructive" onClick={handleDelete}>删除</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
