import { useState, useEffect, useCallback } from 'react'
import { Plus, Search, Pencil, Trash2, Loader2, MoreHorizontal, Monitor } 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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { getClientList, createClient, updateClient, deleteClient } from '@/api/system/client'
import type { SystemClient } from '@/api/system'

export default function ClientsPage() {
  const [clients, setClients] = useState<SystemClient[]>([])
  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: '', clientId: '', name: '', grantType: 'password', activeTimeout: 3600 })
  const [submitting, setSubmitting] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [toDelete, setToDelete] = useState<SystemClient | null>(null)

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

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

  const handleAdd = () => { setIsEdit(false); setForm({ id: '', clientId: '', name: '', grantType: 'password', activeTimeout: 3600 }); setDialogOpen(true) }
  const handleEdit = (c: SystemClient) => { setIsEdit(true); setForm({ id: c.id, clientId: c.clientId, name: c.name, grantType: c.grantType || '', activeTimeout: c.activeTimeout || 3600 }); setDialogOpen(true) }

  const handleSubmit = async () => {
    if (!form.clientId || !form.name) return; setSubmitting(true)
    try { if (isEdit) await updateClient({ ...form, id: form.id! }); else await createClient(form); setDialogOpen(false); fetchList() }
    catch (e) { console.error(e) } finally { setSubmitting(false) }
  }

  const handleDelete = async () => {
    if (!toDelete) return
    try { await deleteClient([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"><Monitor 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">
            <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-[200px] h-10 bg-muted/30" value={search} onChange={e => { setSearch(e.target.value); setPage(1) }} /></div>
            <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">客户端ID</TableHead><TableHead className="font-semibold">名称</TableHead>
                <TableHead className="font-semibold">授权方式</TableHead><TableHead className="font-semibold">超时(s)</TableHead><TableHead className="w-[60px]" />
              </TableRow></TableHeader>
              <TableBody>
                {clients.length === 0 ? <TableRow><TableCell colSpan={5} className="h-32 text-center text-muted-foreground">暂无数据</TableCell></TableRow>
                : clients.map(c => (
                  <TableRow key={c.id} className="group hover:bg-muted/30">
                    <TableCell className="pl-6"><Badge className="bg-primary/10 text-primary border-primary/20">{c.clientId}</Badge></TableCell>
                    <TableCell className="font-medium">{c.name}</TableCell>
                    <TableCell className="text-xs text-muted-foreground">{c.grantType}</TableCell>
                    <TableCell className="font-mono text-muted-foreground">{c.activeTimeout}</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(c)}><Pencil className="mr-2 h-4 w-4" />编辑</DropdownMenuItem>
                          <DropdownMenuItem className="text-destructive" onClick={() => { setToDelete(c); 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-[460px]"><DialogHeader><DialogTitle>{isEdit ? '编辑客户端' : '新增客户端'}</DialogTitle><DialogDescription>配置微服务客户端信息</DialogDescription></DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2"><Label>客户端ID *</Label><Input value={form.clientId} onChange={e => setForm(f => ({ ...f, clientId: e.target.value }))} placeholder="如: plant" /></div>
            <div className="grid gap-2"><Label>名称 *</Label><Input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} placeholder="如: Plant 花园服务" /></div>
            <div className="grid gap-2"><Label>授权方式</Label><Input value={form.grantType} onChange={e => setForm(f => ({ ...f, grantType: e.target.value }))} placeholder="password,refresh_token" /></div>
            <div className="grid gap-2"><Label>超时时间(秒)</Label><Input type="number" value={form.activeTimeout} onChange={e => setForm(f => ({ ...f, activeTimeout: parseInt(e.target.value) || 0 }))} /></div>
          </div>
          <DialogFooter><Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button><Button onClick={handleSubmit} disabled={submitting || !form.clientId || !form.name}>{submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : '保存'}</Button></DialogFooter>
        </DialogContent>
      </Dialog>

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