import { useState, useEffect } from 'react'
import { Plus, RefreshCw, Edit, Trash2, MenuSquare } 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 { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'

import { getMenuTree, createMenu, updateMenu, deleteMenu } from '@/api/system/menu'
import type { SystemMenu } from '@/api/system'
import * as Icons from 'lucide-react'

// Tree Row Component
function MenuRow({ 
  item, depth = 0, onEdit, onDelete, onAddChild 
}: { 
  item: SystemMenu; depth?: number; onEdit: (m: SystemMenu) => void; onDelete: (id: string) => void; onAddChild: (id: string) => void 
}) {
  const [expanded, setExpanded] = useState(true)
  const hasChildren = item.children && item.children.length > 0
  
  // Try to find the exact icon, otherwise try stripping 'Icon' prefix (if from old DB data), fallback to Circle
  const exactIcon = (Icons as any)[item.icon || '']
  const strippedIcon = item.icon?.startsWith('Icon') ? (Icons as any)[item.icon.substring(4)] : undefined
  const IconCmp = exactIcon || strippedIcon || Icons.Circle

  return (
    <>
      <TableRow className={`group transition-colors ${depth === 0 ? 'bg-muted/20 hover:bg-muted/30 border-b-2 border-b-muted/50' : 'hover:bg-muted/10'}`}>
        <TableCell className="font-medium py-3">
          <div className="flex items-center" style={{ paddingLeft: `${depth * 28}px` }}>
            {depth > 0 && (
              <div className="w-4 h-px bg-border/80 mr-2 -ml-2" /> // L-shape connector
            )}
            <div className="flex items-center gap-2">
              {hasChildren ? (
                <button 
                  onClick={() => setExpanded(!expanded)} 
                  className="flex items-center justify-center w-5 h-5 rounded border border-border/60 bg-background hover:bg-muted hover:text-foreground text-muted-foreground transition-all shadow-sm"
                >
                  {expanded ? <Icons.Minus className="h-3 w-3" /> : <Plus className="h-3 w-3" />}
                </button>
              ) : <span className="w-5" />}
              
              <div className={`flex items-center gap-2 px-2 py-1 rounded-md ${depth === 0 ? 'text-foreground font-semibold' : 'text-muted-foreground font-medium'}`}>
                <IconCmp className={`h-4 w-4 ${depth === 0 ? 'text-primary' : 'opacity-70'}`} />
                {item.title}
              </div>
            </div>
          </div>
        </TableCell>
        <TableCell className="text-muted-foreground text-sm font-mono">
          {item.path ? (
            <span className="bg-muted px-2 py-0.5 rounded text-xs">{item.path}</span>
          ) : '-'}
        </TableCell>
        <TableCell>
          <Badge variant={item.category === 1 ? "default" : "secondary"} className={item.category === 1 ? 'bg-primary/10 text-primary hover:bg-primary/20 shadow-none' : 'font-normal shadow-none'}>
            {item.category === 1 ? '目录/菜单' : '操作权限'}
          </Badge>
        </TableCell>
        <TableCell>
          <span className="bg-muted/50 text-muted-foreground border border-border/40 px-2 py-0.5 rounded-md text-xs font-mono">{item.sort}</span>
        </TableCell>
        <TableCell className="text-right pr-6">
          <div className="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
            <Button variant="ghost" size="sm" className="h-7 px-2 text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50 dark:hover:bg-emerald-950/30" onClick={() => onAddChild(item.id)}>
              <Plus className="h-3.5 w-3.5 mr-1" /> 子项
            </Button>
            <Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-blue-500 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-950/30" onClick={() => onEdit(item)}>
              <Edit className="h-3.5 w-3.5" />
            </Button>
            <Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-red-500 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-950/30" onClick={() => onDelete(item.id)}>
              <Trash2 className="h-3.5 w-3.5" />
            </Button>
          </div>
        </TableCell>
      </TableRow>
      {expanded && hasChildren && item.children!.map(child => (
        <MenuRow key={child.id} item={child} depth={depth + 1} onEdit={onEdit} onDelete={onDelete} onAddChild={onAddChild} />
      ))}
    </>
  )
}

const commonIcons = [
  'LayoutDashboard', 'Users', 'User', 'Shield', 'MessageSquare', 'FolderTree', 'Leaf', 
  'Settings', 'Folder', 'Book', 'Home', 'Monitor', 'FileText', 'Bot', 'Radio', 
  'Image', 'Music', 'ScrollText', 'Trophy', 'Award', 'Star', 'Gift', 'List', 'Menu', 
  'Link', 'Activity', 'BarChart2', 'PieChart', 'Calendar', 'Camera', 'Check', 'Circle'
]

function IconPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) {
  const IconCmp = (Icons as any)[value] || Icons.Circle
  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button variant="outline" className="w-full justify-start gap-2">
          {value ? <IconCmp className="h-4 w-4" /> : <Icons.Circle className="h-4 w-4 opacity-50" />}
          <span className="truncate">{value || '选择图标'}</span>
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[320px] p-2" side="right" align="start">
        <div className="grid grid-cols-8 gap-1">
          {commonIcons.map(name => {
            const Cmp = (Icons as any)[name]
            return (
              <Button key={name} variant="ghost" size="icon" className={`h-8 w-8 rounded ${value === name ? 'bg-primary/20 text-primary hover:bg-primary/30' : 'hover:bg-muted'}`} onClick={() => onChange(name)} title={name}>
                {Cmp && <Cmp className="h-4 w-4" />}
              </Button>
            )
          })}
        </div>
      </PopoverContent>
    </Popover>
  )
}

export default function Menus() {
  const [menus, setMenus] = useState<SystemMenu[]>([])
  const [loading, setLoading] = useState(false)
  
  // Dialog State
  const [dialogOpen, setDialogOpen] = useState(false)
  const [editingMenu, setEditingMenu] = useState<SystemMenu | null>(null)
  const [formData, setFormData] = useState({ title: '', name: '', path: '', code: '', permission: '', icon: '', sort: 0, category: 1, parentId: '' })

  const fetchMenus = async () => {
    setLoading(true)
    try {
      const res = await getMenuTree()
      if (res) setMenus(res)
    } finally { setLoading(false) }
  }

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

  // Flatten menus for Parent Selection
  const getFlatMenuOptions = (items: SystemMenu[], prefix = '') => {
    let options: { id: string; title: string }[] = []
    items.forEach(item => {
      options.push({ id: item.id, title: `${prefix}${item.title}` })
      if (item.children?.length) {
        options = options.concat(getFlatMenuOptions(item.children, prefix + '— '))
      }
    })
    return options
  }
  const flatMenuOptions = getFlatMenuOptions(menus)

  const openCreateDialog = (parentId: string = '') => {
    setEditingMenu(null)
    setFormData({ title: '', name: '', path: '', code: '', permission: '', icon: '', sort: 1, category: 1, parentId })
    setDialogOpen(true)
  }

  const openEditDialog = (menu: SystemMenu) => {
    setEditingMenu(menu)
    setFormData({ 
      title: menu.title || '', name: menu.name || '', path: menu.path || '', 
      code: menu.code || '', permission: menu.permission || '',
      icon: menu.icon || '', sort: menu.sort || 1, 
      category: menu.category || 1, parentId: menu.parentId || '' 
    })
    setDialogOpen(true)
  }

  const handleSave = async () => {
    if (editingMenu) await updateMenu({ id: editingMenu.id, ...formData })
    else await createMenu(formData)
    setDialogOpen(false)
    fetchMenus()
  }

  const handleDelete = async (id: string) => {
    if (confirm('确定要删除这个菜单节点吗？其子节点也会受到影响。')) {
      await deleteMenu([id])
      fetchMenus()
    }
  }

  return (
    <div className="space-y-6 animate-fadeIn pb-8">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">菜单管理</h1>
        <p className="text-muted-foreground mt-1">配置系统左侧导航菜单、路由及页面操作权限。</p>
      </div>

      <Card className="border-border/60 shadow-soft">
        <CardHeader className="pb-3 border-b border-border/40">
          <div className="flex justify-between items-center">
            <CardTitle className="text-lg flex items-center gap-2">
              <MenuSquare className="h-5 w-5 text-primary" /> 菜单树
            </CardTitle>
            <Button size="sm" onClick={() => openCreateDialog('')} className="h-9 gap-1.5">
              <Plus className="h-4 w-4" /> 新增根菜单
            </Button>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHeader className="bg-muted/30">
              <TableRow>
                <TableHead className="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>
              ) : menus.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="h-32 text-center text-muted-foreground">暂无数据</TableCell>
                </TableRow>
              ) : (
                menus.map(menu => (
                  <MenuRow key={menu.id} item={menu} onEdit={openEditDialog} onDelete={handleDelete} onAddChild={openCreateDialog} />
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>{editingMenu ? '编辑菜单' : '新增菜单'}</DialogTitle>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">菜单类型</Label>
              <div className="col-span-3 flex items-center gap-6">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input type="radio" className="accent-primary" checked={formData.category === 1} onChange={() => setFormData({ ...formData, category: 1, permission: '' })} />
                  <span className="text-sm font-medium">目录/菜单</span>
                </label>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input type="radio" className="accent-primary" checked={formData.category === 2} onChange={() => setFormData({ ...formData, category: 2, path: '', icon: '' })} />
                  <span className="text-sm font-medium">按钮/权限</span>
                </label>
              </div>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">上级菜单</Label>
              <div className="col-span-3">
                <Select value={formData.parentId || 'root'} onValueChange={v => setFormData({ ...formData, parentId: v === 'root' ? '' : v })}>
                  <SelectTrigger>
                    <SelectValue placeholder="请选择上级菜单" />
                  </SelectTrigger>
                  <SelectContent className="max-h-[280px]">
                    <SelectItem value="root" className="text-primary font-medium">根目录 (Root)</SelectItem>
                    {flatMenuOptions.filter(m => m.id !== editingMenu?.id).map(opt => (
                      <SelectItem key={opt.id} value={opt.id}>{opt.title}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="title" className="text-right">{formData.category === 1 ? '菜单名称' : '权限名称'}</Label>
              <Input id="title" value={formData.title} onChange={e => setFormData({ ...formData, title: e.target.value })} className="col-span-3" placeholder={formData.category === 1 ? '如: 用户管理' : '如: 新增用户'} />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="name" className="text-right">路由 Name</Label>
              <Input id="name" value={formData.name} onChange={e => setFormData({ ...formData, name: e.target.value })} className="col-span-3" placeholder="如: UserList" />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="code" className="text-right">标识 Code</Label>
              <Input id="code" value={formData.code} onChange={e => setFormData({ ...formData, code: e.target.value })} className="col-span-3" placeholder="如: systemRole" />
            </div>
            {formData.category === 1 && (
              <>
                <div className="grid grid-cols-4 items-center gap-4">
                  <Label htmlFor="path" className="text-right">路由路径</Label>
                  <Input id="path" value={formData.path} onChange={e => setFormData({ ...formData, path: e.target.value })} className="col-span-3" placeholder="如: /system/users" />
                </div>
                <div className="grid grid-cols-4 items-center gap-4">
                  <Label htmlFor="icon" className="text-right">图标</Label>
                  <div className="col-span-3">
                    <IconPicker value={formData.icon} onChange={v => setFormData({ ...formData, icon: v })} />
                  </div>
                </div>
              </>
            )}
            {formData.category === 2 && (
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="permission" className="text-right">操作权限</Label>
                <Input id="permission" value={formData.permission} onChange={e => setFormData({ ...formData, permission: e.target.value })} className="col-span-3" placeholder="如: sys:user:add" />
              </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>
    </div>
  )
}
