'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { usePermissions } from '@/hooks/usePermissions';
import { useTranslation } from '@/hooks/useTranslation';

interface PermissionGuardProps {
  children: React.ReactNode;
  /**
   * 需要的权限列表（满足任一即可）
   */
  permissions?: string[];
  /**
   * 需要的角色列表（满足任一即可）
   */
  roles?: string[];
  /**
   * 是否需要所有权限（默认 false，满足任一即可）
   */
  requireAll?: boolean;
  /**
   * 无权限时的回退页面（默认重定向到 dashboard）
   */
  fallback?: React.ReactNode;
  /**
   * 无权限时的重定向路径
   */
  redirectTo?: string;
}

export function PermissionGuard({
  children,
  permissions = [],
  roles = [],
  requireAll = false,
  fallback,
  redirectTo = '/overview',
}: PermissionGuardProps) {
  const router = useRouter();
  const {
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    hasRole,
    hasAnyRole,
    isAdmin,
    loading,
  } = usePermissions();
  const { t } = useTranslation();
  
  const [hasAccess, setHasAccess] = useState(false);
  const [checked, setChecked] = useState(false);

  useEffect(() => {
    if (loading) return;

    // 管理员默认有所有权限
    if (isAdmin) {
      setHasAccess(true);
      setChecked(true);
      return;
    }

    let access = false;

    // 检查权限
    if (permissions.length > 0) {
      if (requireAll) {
        access = hasAllPermissions(permissions);
      } else {
        access = hasAnyPermission(permissions);
      }
    }

    // 检查角色
    if (!access && roles.length > 0) {
      access = hasAnyRole(roles);
    }

    // 如果既没有权限要求也没有角色要求，默认允许访问
    if (permissions.length === 0 && roles.length === 0) {
      access = true;
    }

    setHasAccess(access);
    setChecked(true);
  }, [
    loading,
    isAdmin,
    permissions,
    roles,
    requireAll,
    hasAllPermissions,
    hasAnyPermission,
    hasAnyRole,
  ]);

  // 加载中
  if (!checked || loading) {
    return (
      <div className="min-h-screen flex items-center justify-center" style={{ backgroundColor: '#f0f2f5' }}>
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 mx-auto" style={{ borderColor: '#1890ff' }}></div>
          <p className="mt-4 text-sm" style={{ color: '#666' }}>
            {t.common.checkingPermission}
          </p>
        </div>
      </div>
    );
  }

  // 无权限
  if (!hasAccess) {
    if (fallback) {
      return <>{fallback}</>;
    }
    
    return (
      <div className="min-h-screen flex items-center justify-center" style={{ backgroundColor: '#f0f2f5' }}>
        <div className="text-center">
          <svg className="w-16 h-16 mx-auto text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
          </svg>
          <h2 className="mt-4 text-lg font-semibold" style={{ color: '#333' }}>
            {t.common.permissionDenied}
          </h2>
          <p className="mt-2 text-sm" style={{ color: '#666' }}>
            {t.common.permissionDeniedDetail}
          </p>
          <button
            onClick={() => router.back()}
            className="mt-6 px-6 py-2 rounded-lg text-white hover:opacity-90 transition-opacity"
            style={{ backgroundColor: '#1890ff' }}
          >
            {t.common.back}
          </button>
        </div>
      </div>
    );
  }

  // 有权限，渲染子组件
  return <>{children}</>;
}

/**
 * 用于条件渲染的权限检查组件
 */
interface CanProps {
  children: React.ReactNode;
  permission?: string;
  permissions?: string[];
  role?: string;
  roles?: string[];
  requireAll?: boolean;
  fallback?: React.ReactNode;
}

export function Can({
  children,
  permission,
  permissions = [],
  role,
  roles = [],
  requireAll = false,
  fallback = null,
}: CanProps) {
  const {
    hasPermission: checkPermission,
    hasAnyPermission,
    hasAllPermissions,
    hasRole: checkRole,
    hasAnyRole,
    isAdmin,
  } = usePermissions();

  // 管理员默认有所有权限
  if (isAdmin) {
    return <>{children}</>;
  }

  let hasAccess = false;

  // 检查单个权限
  if (permission) {
    hasAccess = checkPermission(permission);
  }

  // 检查多个权限
  if (!hasAccess && permissions.length > 0) {
    if (requireAll) {
      hasAccess = hasAllPermissions(permissions);
    } else {
      hasAccess = hasAnyPermission(permissions);
    }
  }

  // 检查单个角色
  if (!hasAccess && role) {
    hasAccess = checkRole(role);
  }

  // 检查多个角色
  if (!hasAccess && roles.length > 0) {
    hasAccess = hasAnyRole(roles);
  }

  if (hasAccess) {
    return <>{children}</>;
  }

  return <>{fallback}</>;
}
