import { useState, useEffect } from 'react'
import { Plus, Search, RefreshCw, Edit, Trash2, Shield, Settings2 } from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import { ScrollArea } from '@/components/ui/scroll-area'

import { getRoleList, createRole, updateRole, deleteRole } from '@/api/system/role'
import { getMenuTree } from '@/api/system/menu'
import type { SystemRole, SystemMenu } from '@/api/system'

export default function Roles() {
  const [roles, setRoles] = useState<SystemRole[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [search, setSearch] = useState({ name: '' })
  
  // Dialog State
  const [dialogOpen, setDialogOpen] = useState(false)
  const [editingRole, setEditingRole] = useState<SystemRole | null>(null)
  const [formData, setFormData] = useState({ name: '', code: '', sort: 0 })

  // Menu Permissions Dialog State
  const [permDialogOpen, setPermDialogOpen] = useState(false)
  const [allMenus, setAllMenus] = useState<SystemMenu[]>([])
  const [selectedMenuIds, setSelectedMenuIds] = useState<string[]>([])
  const [activeRole, setActiveRole] = useState<SystemRole | null>(null)

  const fetchRoles = async () => {
    setLoading(true)
    try {
      const res = await getRoleList({ current: 1, pageSize: 10, ...search })
      if (res) {
        setRoles(res.list)
        setTotal(res.total)
      }
    } finally {
      setLoading(false)
    }
  }

  const fetchMenus = async () => {
    const res = await getMenuTree()
    if (res) setAllMenus(res)
  }

  useEffect(() => { 
    fetchRoles()
    fetchMenus()
  }, [])

  const handleSearch = () => fetchRoles()
  const handleReset = () => { setSearch({ name: '' }); setTimeout(() => fetchRoles(), 0) }

  const openCreateDialog = () => {
    setEditingRole(null)
    setFormData({ name: '', code: '', sort: 1 })
    setDialogOpen(true)
  }

  const openEditDialog = (role: SystemRole) => {
    setEditingRole(role)
    setFormData({ name: role.name, code: role.code, sort: role.sort || 1 })
    setDialogOpen(true)
  }

  const handleSave = async () => {
    if (editingRole) await updateRole({ id: editingRole.id, ...formData })
    else await createRole(formData)
    setDialogOpen(false)
    fetchRoles()
  }

  const handleDelete = async (id: string) => {
    if (confirm('确定要删除这个角色吗？')) {
      await deleteRole([id])
      fetchRoles()
    }
  }

  const openPermDialog = (role: SystemRole) => {
    setActiveRole(role)
    // Actually get the role's menus
    setSelectedMenuIds(role.menuIds || [])
    setPermDialogOpen(true)
  }

  const handleSavePerms = async () => {
    if (activeRole) {
      await updateRole({ id: activeRole.id, menuIds: selectedMenuIds })
      fetchRoles()
    }
    setPermDialogOpen(false)
  }

  const toggleMenu = (id: string, checked: boolean) => {
    if (checked) setSelectedMenuIds(prev => [...prev, id])
    else setSelectedMenuIds(prev => prev.filter(i => i !== id))
  }

  const renderMenuTree = (menus: SystemMenu[], depth = 0) => {
    return menus.map(menu => (
      <div key={menu.id} className="flex flex-col" style={{ marginLeft: depth > 0 ? 24 : 0 }}>
        <div className="flex items-center space-x-2 py-2">
          <Checkbox 
            id={`menu-${menu.id}`} 
            checked={selectedMenuIds.includes(menu.id)}
            onCheckedChange={c => toggleMenu(menu.id, c as boolean)}
          />
          <Label htmlFor={`menu-${menu.id}`} className="font-normal cursor-pointer flex items-center gap-2">
            {menu.title} {menu.category === 2 && <span className="text-[10px] bg-muted px-1 rounded text-muted-foreground">按钮</span>}
          </Label>
        </div>
        {menu.children && menu.children.length > 0 && (
          <div className="border-l border-border/40 ml-2 pl-2">
            {renderMenuTree(menu.children, depth + 1)}
          </div>
        )}
      </div>
    ))
  }

  return (
    <div className="space-y-6 animate-fadeIn">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">角色管理</h1>
        <p className="text-muted-foreground mt-1">配置系统角色，用于 RBAC 权限分配。</p>
      </div>

      <Card className="border-border/60 shadow-soft">
        <CardHeader className="pb-3 border-b border-border/40">
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <CardTitle className="text-lg flex items-center gap-2">
              <Shield className="h-5 w-5 text-primary" /> 角色列表
            </CardTitle>
            
            <div className="flex flex-wrap items-center gap-3">
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索角色名..."
                  className="pl-9 w-48 h-9"
                  value={search.name}
                  onChange={e => setSearch({ ...search, name: e.target.value })}
                  onKeyDown={e => e.key === 'Enter' && handleSearch()}
                />
              </div>
              <Button variant="outline" size="sm" onClick={handleReset} className="h-9 px-3">重置</Button>
              <Button size="sm" onClick={openCreateDialog} className="h-9 gap-1.5">
                <Plus className="h-4 w-4" /> 新增角色
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHeader className="bg-muted/30">
              <TableRow>
                <TableHead className="w-[150px] pl-6">角色名称</TableHead>
                <TableHead>角色代码</TableHead>
                <TableHead>排序</TableHead>
                <TableHead>创建时间</TableHead>
                <TableHead className="text-right pr-6">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={5} className="h-32 text-center text-muted-foreground">
                    <RefreshCw className="h-6 w-6 animate-spin mx-auto mb-2 text-primary/50" /> 加载中...
                  </TableCell>
                </TableRow>
              ) : roles.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="h-32 text-center text-muted-foreground">暂无数据</TableCell>
                </TableRow>
              ) : (
                roles.map(role => (
                  <TableRow key={role.id} className="hover:bg-muted/20">
                    <TableCell className="font-medium pl-6">{role.name}</TableCell>
                    <TableCell className="font-mono text-xs">{role.code}</TableCell>
                    <TableCell>{role.sort}</TableCell>
                    <TableCell className="text-muted-foreground text-sm">
                      -
                    </TableCell>
                    <TableCell className="text-right pr-6">
                      <div className="flex items-center justify-end gap-2">
                        <Button variant="ghost" size="sm" className="h-8 gap-1" onClick={() => openEditDialog(role)}>
                          <Edit className="h-3.5 w-3.5 text-blue-500" /> 编辑
                        </Button>
                        <Button variant="ghost" size="sm" className="h-8 gap-1" onClick={() => openPermDialog(role)}>
                          <Settings2 className="h-3.5 w-3.5 text-emerald-500" /> 菜单权限
                        </Button>
                        <Button variant="ghost" size="sm" className="h-8 gap-1 hover:text-red-500" onClick={() => handleDelete(role.id)}>
                          <Trash2 className="h-3.5 w-3.5 text-red-500" /> 删除
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
          
          <div className="flex items-center justify-between px-6 py-4 border-t border-border/40 text-sm text-muted-foreground">
            <div>共 {total} 条记录</div>
            <div className="flex items-center gap-2">
              <Button variant="outline" size="sm" disabled>上一页</Button>
              <Button variant="outline" size="sm" disabled>下一页</Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>{editingRole ? '编辑角色' : '新增角色'}</DialogTitle>
            <DialogDescription>
              {editingRole ? '修改角色的基本信息。' : '在系统中创建一个新角色。'}
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="name" className="text-right">角色名称</Label>
              <Input id="name" value={formData.name} onChange={e => setFormData({ ...formData, name: e.target.value })} className="col-span-3" />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="code" className="text-right">角色代码</Label>
              <Input id="code" value={formData.code} onChange={e => setFormData({ ...formData, code: e.target.value })} className="col-span-3" />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="sort" className="text-right">排序</Label>
              <Input id="sort" type="number" value={formData.sort} onChange={e => setFormData({ ...formData, sort: parseInt(e.target.value) || 0 })} className="col-span-3" />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
            <Button onClick={handleSave}>保存更改</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={permDialogOpen} onOpenChange={setPermDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>分配菜单权限</DialogTitle>
            <DialogDescription>
              为角色 <span className="font-semibold text-foreground">{activeRole?.name}</span> 分配可访问的菜单和按钮权限。
            </DialogDescription>
          </DialogHeader>
          
          <ScrollArea className="h-[400px] mt-4 pr-4 border rounded-md p-4 bg-muted/10">
            {renderMenuTree(allMenus)}
          </ScrollArea>
          
          <DialogFooter className="mt-4">
            <Button variant="outline" onClick={() => setPermDialogOpen(false)}>取消</Button>
            <Button onClick={handleSavePerms}>保存权限</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
