import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useToast } from '@/components/ui/use-toast';
import { Loader2, KeyRound, Folder, Key } from 'lucide-react';
import { getPermissionTree } from '../service';

interface PermissionDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onConfirm: (permissionIds: number[]) => Promise<void>;
  defaultCheckedKeys?: number[];
}

interface Permission {
  id: number;
  code: string;
  name: string;
  type: string;
  sort: number;
}

interface MenuItem {
  id: number;
  name: string;
  path: string;
  icon: string;
  type: number;
  permissionChildren: MenuItem[];
  permissions: Permission[];
}

/**
 * 权限分配对话框（使用 Accordion 实现树形结构）
 */
const PermissionDialog: React.FC<PermissionDialogProps> = ({
  open,
  onOpenChange,
  onConfirm,
  defaultCheckedKeys = []
}) => {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [menuTree, setMenuTree] = useState<MenuItem[]>([]);
  const [checkedPermissionIds, setCheckedPermissionIds] = useState<number[]>([]);

  useEffect(() => {
    const loadPermissionTree = async () => {
      if (!open) return;
      
      setLoading(true);
      try {
        const response = await getPermissionTree();
        setMenuTree(response);
        setCheckedPermissionIds(defaultCheckedKeys);
      } catch (error) {
        console.error('获取权限树失败:', error);
        toast({
          title: '加载失败',
          description: error instanceof Error ? error.message : '未知错误',
          variant: 'destructive'
        });
      } finally {
        setLoading(false);
      }
    };

    loadPermissionTree();
  }, [open, defaultCheckedKeys]);

  // 切换权限选中状态
  const handleTogglePermission = (permissionId: number) => {
    setCheckedPermissionIds(prev =>
      prev.includes(permissionId)
        ? prev.filter(id => id !== permissionId)
        : [...prev, permissionId]
    );
  };

  // 递归获取菜单下所有权限ID
  const getAllPermissionIds = (menu: MenuItem): number[] => {
    const ids: number[] = [];
    if (menu.permissions) {
      ids.push(...menu.permissions.map(p => p.id));
    }
    if (menu.permissionChildren) {
      menu.permissionChildren.forEach(child => {
        ids.push(...getAllPermissionIds(child));
      });
    }
    return ids;
  };

  // 检查菜单下所有权限是否全选
  const isMenuFullyChecked = (menu: MenuItem): boolean => {
    const allIds = getAllPermissionIds(menu);
    return allIds.length > 0 && allIds.every(id => checkedPermissionIds.includes(id));
  };

  // 检查菜单下是否有部分权限选中
  const isMenuPartiallyChecked = (menu: MenuItem): boolean => {
    const allIds = getAllPermissionIds(menu);
    const checkedCount = allIds.filter(id => checkedPermissionIds.includes(id)).length;
    return checkedCount > 0 && checkedCount < allIds.length;
  };

  // 切换菜单的全选/取消全选
  const handleToggleMenu = (menu: MenuItem) => {
    const allIds = getAllPermissionIds(menu);
    const isFullyChecked = isMenuFullyChecked(menu);
    
    if (isFullyChecked) {
      // 取消全选
      setCheckedPermissionIds(prev => prev.filter(id => !allIds.includes(id)));
    } else {
      // 全选
      setCheckedPermissionIds(prev => {
        const newIds = [...prev];
        allIds.forEach(id => {
          if (!newIds.includes(id)) {
            newIds.push(id);
          }
        });
        return newIds;
      });
    }
  };

  // 渲染菜单项
  const renderMenuItem = (menu: MenuItem, level: number = 0): React.ReactNode => {
    const hasChildren = menu.permissionChildren && menu.permissionChildren.length > 0;
    const hasPermissions = menu.permissions && menu.permissions.length > 0;
    const isChecked = isMenuFullyChecked(menu);
    const isPartial = isMenuPartiallyChecked(menu);

    if (!hasChildren && !hasPermissions) {
      return null;
    }

    return (
      <div key={menu.id} className={level > 0 ? 'ml-4' : ''}>
        {hasChildren ? (
          <AccordionItem value={`menu-${menu.id}`} className="border-b-0">
            <AccordionTrigger className="py-2 hover:no-underline hover:bg-muted/50 px-2 rounded">
              <div className="flex items-center gap-2 flex-1">
                <Checkbox
                  checked={isChecked}
                  ref={(el) => {
                    if (el) {
                      // @ts-ignore - 设置 indeterminate 状态
                      el.indeterminate = isPartial && !isChecked;
                    }
                  }}
                  onCheckedChange={() => handleToggleMenu(menu)}
                  onClick={(e) => e.stopPropagation()}
                />
                <Folder className="h-4 w-4 text-blue-500" />
                <span className="text-sm font-medium">{menu.name}</span>
              </div>
            </AccordionTrigger>
            <AccordionContent className="pb-0 pt-2">
              {/* 渲染当前菜单的权限 */}
              {hasPermissions && (
                <div className="space-y-2 mb-2 ml-8">
                  {menu.permissions.map(permission => (
                    <div key={permission.id} className="flex items-center gap-2 py-1">
                      <Checkbox
                        id={`permission-${permission.id}`}
                        checked={checkedPermissionIds.includes(permission.id)}
                        onCheckedChange={() => handleTogglePermission(permission.id)}
                      />
                      <label
                        htmlFor={`permission-${permission.id}`}
                        className="text-sm cursor-pointer flex items-center gap-2"
                      >
                        <Key className="h-3 w-3 text-muted-foreground" />
                        {permission.name}
                      </label>
                    </div>
                  ))}
                </div>
              )}
              {/* 递归渲染子菜单 */}
              <Accordion type="multiple" className="w-full">
                {menu.permissionChildren.map(child => renderMenuItem(child, level + 1))}
              </Accordion>
            </AccordionContent>
          </AccordionItem>
        ) : (
          // 没有子菜单，只显示权限列表
          <div className="py-2 px-2">
            <div className="flex items-center gap-2 mb-2">
              <Checkbox
                checked={isChecked}
                ref={(el) => {
                  if (el) {
                    // @ts-ignore
                    el.indeterminate = isPartial && !isChecked;
                  }
                }}
                onCheckedChange={() => handleToggleMenu(menu)}
              />
              <Folder className="h-4 w-4 text-blue-500" />
              <span className="text-sm font-medium">{menu.name}</span>
            </div>
            {hasPermissions && (
              <div className="space-y-2 ml-8">
                {menu.permissions.map(permission => (
                  <div key={permission.id} className="flex items-center gap-2 py-1">
                    <Checkbox
                      id={`permission-${permission.id}`}
                      checked={checkedPermissionIds.includes(permission.id)}
                      onCheckedChange={() => handleTogglePermission(permission.id)}
                    />
                    <label
                      htmlFor={`permission-${permission.id}`}
                      className="text-sm cursor-pointer flex items-center gap-2"
                    >
                      <Key className="h-3 w-3 text-muted-foreground" />
                      {permission.name}
                    </label>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  const handleSubmit = async () => {
    setSubmitting(true);
    try {
      await onConfirm(checkedPermissionIds);
      onOpenChange(false);
    } catch (error) {
      console.error('分配权限失败:', error);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[700px] max-h-[80vh]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <KeyRound className="h-5 w-5" /> 分配权限
          </DialogTitle>
        </DialogHeader>
        <div className="overflow-y-auto max-h-[500px] pr-2">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-6 w-6 animate-spin mr-2" />
              <span className="text-sm text-muted-foreground">加载中...</span>
            </div>
          ) : menuTree.length > 0 ? (
            <Accordion type="multiple" className="w-full">
              {menuTree.map(menu => renderMenuItem(menu))}
            </Accordion>
          ) : (
            <div className="flex items-center justify-center py-12 text-muted-foreground">
              暂无权限数据
            </div>
          )}
        </div>
        <DialogFooter>
          <div className="flex items-center justify-between w-full">
            <span className="text-sm text-muted-foreground">
              已选择 {checkedPermissionIds.length} 个权限
            </span>
            <div className="flex gap-2">
              <Button variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
                取消
              </Button>
              <Button onClick={handleSubmit} disabled={submitting || loading}>
                {submitting ? '保存中...' : '确定'}
              </Button>
            </div>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default PermissionDialog;
