import { useState, useEffect } from 'react'
import { Plus, Search, RefreshCw, Edit, Trash2, ShieldCheck, MoreHorizontal } 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 { Badge } from '@/components/ui/badge'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'

import { getUserList, createUser, updateUser, deleteUser, getUserDetail, assignUserRoles } from '@/api/system/user'
import { getRoleList } from '@/api/system/role'
import type { SystemUser, SystemRole } from '@/api/system'

export default function UserManage() {
  const [users, setUsers] = useState<SystemUser[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [search, setSearch] = useState({ account: '', name: '' })
  
  // All Roles for assignment
  const [allRoles, setAllRoles] = useState<SystemRole[]>([])

  // Dialog State
  const [dialogOpen, setDialogOpen] = useState(false)
  const [editingUser, setEditingUser] = useState<SystemUser | null>(null)
  const [formData, setFormData] = useState({ account: '', name: '', phone: '', clientId: '', roleIds: [] as string[] })

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

  const fetchRoles = async () => {
    const res = await getRoleList({ current: 1, pageSize: 100 })
    if (res) setAllRoles(res.list)
  }

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

  const handleSearch = () => fetchUsers()

  const handleReset = () => {
    setSearch({ account: '', name: '' })
    setTimeout(() => fetchUsers(), 0)
  }

  const openCreateDialog = () => {
    setEditingUser(null)
    setFormData({ account: '', name: '', phone: '', clientId: '', roleIds: [] })
    setDialogOpen(true)
  }

  const openEditDialog = async (user: SystemUser) => {
    setEditingUser(user)
    setFormData({ 
      account: user.account, name: user.name, phone: user.phone || '', clientId: '',
      roleIds: []
    })
    setDialogOpen(true)

    const detail = await getUserDetail(user.id)
    if (detail) {
      setFormData(prev => ({ ...prev, roleIds: detail.roleIds || [] }))
    }
  }

  const handleSave = async () => {
    if (editingUser) {
      await updateUser({ id: editingUser.id, account: formData.account, name: formData.name, phone: formData.phone })
      await assignUserRoles({ userId: editingUser.id, roleIds: formData.roleIds })
    } else {
      await createUser({ ...formData, password: '123' }) 
    }
    setDialogOpen(false)
    fetchUsers()
  }

  const handleDelete = async (id: string) => {
    if (confirm('确定要删除这个用户吗？')) {
      await deleteUser([id])
      fetchUsers()
    }
  }

  const toggleRole = (roleId: string, checked: boolean) => {
    if (checked) {
      setFormData(prev => ({ ...prev, roleIds: [...prev.roleIds, roleId] }))
    } else {
      setFormData(prev => ({ ...prev, roleIds: prev.roleIds.filter(id => id !== roleId) }))
    }
  }

  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">管理系统和各个客户端(Plant, Radio等)的用户访问权限及角色绑定。</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">
              <ShieldCheck 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-40 h-9"
                  value={search.account}
                  onChange={e => setSearch({ ...search, account: e.target.value })}
                  onKeyDown={e => e.key === 'Enter' && handleSearch()}
                />
              </div>
              <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-40 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-[100px] pl-6">账号</TableHead>
                <TableHead>姓名</TableHead>
                <TableHead>手机号</TableHead>
                <TableHead>角色</TableHead>
                <TableHead>创建时间</TableHead>
                <TableHead className="text-right pr-6">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={7} 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>
              ) : users.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="h-32 text-center text-muted-foreground">暂无数据</TableCell>
                </TableRow>
              ) : (
                users.map(user => (
                  <TableRow key={user.id} className="hover:bg-muted/20">
                    <TableCell className="font-medium pl-6">{user.account}</TableCell>
                    <TableCell>{user.name}</TableCell>
                    <TableCell>{user.phone || '-'}</TableCell>
                    <TableCell>
                      <div className="flex gap-1 flex-wrap">
                        {user.roles?.map(roleObj => {
                          const name = typeof roleObj === 'string' ? roleObj : roleObj.name
                          const key = typeof roleObj === 'string' ? roleObj : roleObj.id
                          return (
                          <Badge key={key} variant="default" className="text-[10px] h-5 font-normal bg-emerald-500 hover:bg-emerald-600 text-white">
                            {name}
                          </Badge>
                          )
                        }) || <span className="text-muted-foreground text-xs">无角色</span>}
                      </div>
                    </TableCell>
                    <TableCell className="text-muted-foreground text-sm">
                      {user.createdAt ? new Date(user.createdAt * 1000).toLocaleDateString('zh-CN') : '-'}
                    </TableCell>
                    <TableCell className="text-right pr-6">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" className="h-8 w-8 p-0">
                            <span className="sr-only">打开菜单</span>
                            <MoreHorizontal className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuLabel>操作</DropdownMenuLabel>
                          <DropdownMenuItem onClick={() => openEditDialog(user)}>
                            <Edit className="mr-2 h-4 w-4 text-blue-500" /> 编辑 & 赋权
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem onClick={() => handleDelete(user.id)} className="text-red-500 focus:text-red-500 focus:bg-red-50 dark:focus:bg-red-950">
                            <Trash2 className="mr-2 h-4 w-4" /> 删除用户
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </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 for Create/Edit */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>{editingUser ? '编辑用户' : '新增用户'}</DialogTitle>
            <DialogDescription>
              {editingUser ? '修改用户信息并分配角色。' : '在系统中创建一个新用户账号并分配角色。'}
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="account" className="text-right">账号</Label>
              <Input id="account" value={formData.account} onChange={e => setFormData({ ...formData, account: e.target.value })} className="col-span-3" disabled={!!editingUser} />
            </div>
            <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="phone" className="text-right">手机号</Label>
              <Input id="phone" value={formData.phone} onChange={e => setFormData({ ...formData, phone: e.target.value })} className="col-span-3" />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="clientId" className="text-right">客户端</Label>
              <Input id="clientId" placeholder="如: plant, radio" value={formData.clientId} onChange={e => setFormData({ ...formData, clientId: e.target.value })} className="col-span-3" />
            </div>
            
            {/* Roles Assignment */}
            <div className="grid grid-cols-4 items-start gap-4 mt-2">
              <Label className="text-right pt-2">分配角色</Label>
              <div className="col-span-3 grid grid-cols-2 gap-3 p-3 bg-muted/30 rounded-lg border border-border/50">
                {allRoles.map(role => (
                  <div key={role.id} className="flex items-center space-x-2">
                    <Checkbox 
                      id={`role-${role.id}`} 
                      checked={formData.roleIds.includes(role.id)} 
                      onCheckedChange={(checked) => toggleRole(role.id, checked as boolean)} 
                    />
                    <label
                      htmlFor={`role-${role.id}`}
                      className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
                    >
                      {role.name}
                    </label>
                  </div>
                ))}
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
            <Button onClick={handleSave}>保存更改</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
