import { useState, useEffect, useCallback } from 'react'
import { Search, Trash2, Loader2, MoreHorizontal, FileText, ThumbsUp, MessageCircle } 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 { 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 { getPostList, deletePost } from '@/api/plant'
import type { Post } from '@/api/plant'

export default function PostPage() {
  const [posts, setPosts] = useState<Post[]>([])
  const [loading, setLoading] = useState(true)
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [toDelete, setToDelete] = useState<Post | null>(null)

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

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

  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"><FileText className="h-5 w-5 text-primary" />帖子管理 <Badge variant="secondary" className="text-xs">{total}</Badge></CardTitle>
            <CardDescription>管理社区用户发布的帖子</CardDescription>
          </div>
          <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-[200px] h-10 bg-muted/30" value={search} onChange={e => { setSearch(e.target.value); setPage(1) }} /></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>{posts.map(p => (
                <TableRow key={p.id} className="group hover:bg-muted/30">
                  <TableCell className="pl-6 font-medium max-w-[200px] truncate">{p.title}</TableCell>
                  <TableCell><Badge variant="secondary" className="text-xs">{p.topicTitle}</Badge></TableCell>
                  <TableCell className="text-sm">{p.userName}</TableCell>
                  <TableCell><div className="flex items-center gap-3 text-xs text-muted-foreground"><span className="flex items-center gap-1"><ThumbsUp className="h-3 w-3" />{p.likeCount}</span><span className="flex items-center gap-1"><MessageCircle className="h-3 w-3" />{p.commentCount}</span></div></TableCell>
                  <TableCell>{p.status === 1 ? <Badge className="bg-green-500/10 text-green-700 border-green-500/20">正常</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 className="text-destructive" onClick={() => { setToDelete(p); setDeleteOpen(true) }}><Trash2 className="mr-2 h-4 w-4" />删除</DropdownMenuItem></DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}</TableBody></Table>
            </div>
          )}
          {Math.ceil(total/10) > 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>=Math.ceil(total/10)} onClick={()=>setPage(p=>p+1)}>下一页</Button></div></div>}
        </CardContent>
      </Card>
      <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
        <DialogContent><DialogHeader><DialogTitle>确认删除帖子「{toDelete?.title}」？</DialogTitle></DialogHeader>
          <DialogFooter><Button variant="outline" onClick={() => setDeleteOpen(false)}>取消</Button><Button variant="destructive" onClick={async () => { if (toDelete) { await deletePost(toDelete.id); setDeleteOpen(false); fetchList() } }}>删除</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
