import { useState, useEffect, useCallback } from 'react'
import { Plus, Search, Pencil, Trash2, Loader2, MoreHorizontal, GalleryHorizontalEnd } 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 { getBannerList, saveBanner, updateBanner, deleteBanner } from '@/api/plant'
import type { Banner } from '@/api/plant'


export default function BannerPage() {
  const [banners, setBanners] = useState<Banner[]>([])
  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: '', title: '', imageId: '', imageUrl: '', sort: 0, isActive: 1, targetUrl: '' })
  const [submitting, setSubmitting] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [toDelete, setToDelete] = useState<Banner | null>(null)

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

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

  const handleAdd = () => { setIsEdit(false); setForm({ id: '', title: '', imageId: '', imageUrl: '', sort: 0, isActive: 1, targetUrl: '' }); setDialogOpen(true) }
  const handleEdit = (b: Banner) => { setIsEdit(true); setForm({ id: b.id, title: b.title, imageId: b.imageId, imageUrl: b.image?.url || '', sort: b.sort, isActive: b.isActive, targetUrl: b.targetUrl || '' }); setDialogOpen(true) }

  const handleSubmit = async () => {
    if (!form.title) return; setSubmitting(true)
    try { if (isEdit) await updateBanner(form as any); else await saveBanner(form as any); setDialogOpen(false); fetchList() }
    catch (e) { console.error(e) } finally { setSubmitting(false) }
  }

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

  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"><GalleryHorizontalEnd 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="w-[60px]" />
              </TableRow></TableHeader>
              <TableBody>
                {banners.map(b => (
                  <TableRow key={b.id} className="group hover:bg-muted/30">
                    <TableCell className="pl-6">{b.image ? <img src={b.image.url} alt={b.title} className="h-12 w-24 rounded-lg object-cover border" /> : <div className="h-12 w-24 bg-muted/50 rounded-lg" />}</TableCell>
                    <TableCell className="font-medium">{b.title}</TableCell>
                    <TableCell>{b.isActive === 1 ? <Badge className="bg-green-500/10 text-green-700 border-green-500/20">启用</Badge> : <Badge variant="secondary">禁用</Badge>}</TableCell>
                    <TableCell className="font-mono text-muted-foreground">{b.sort}</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(b)}><Pencil className="mr-2 h-4 w-4" />编辑</DropdownMenuItem>
                          <DropdownMenuItem className="text-destructive" onClick={() => { setToDelete(b); 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.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={String(form.isActive)} onValueChange={v => setForm(f => ({ ...f, isActive: parseInt(v) }))}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent><SelectItem value="1">启用</SelectItem><SelectItem value="0">禁用</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="grid gap-2"><Label>跳转链接</Label><Input value={form.targetUrl} onChange={e => setForm(f => ({ ...f, targetUrl: e.target.value }))} placeholder="/pages/wiki/index" /></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>确认删除「{toDelete?.title}」？</DialogTitle></DialogHeader>
          <DialogFooter><Button variant="outline" onClick={() => setDeleteOpen(false)}>取消</Button><Button variant="destructive" onClick={handleDelete}>删除</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
