import { useLocation } from 'react-router-dom';
import { Link } from 'react-router-dom';
import type { ReactElement } from 'react';
import { cn } from '@/lib/utils';
import { useAppSelector } from '@/hooks/redux-hooks';

export interface TabItem {
  label: string;
  path: string;
}

interface PageHeaderProps {
  title: string;
  description?: string;
  tabs?: TabItem[];
}

const defaultTabs: TabItem[] = [
  { label: 'Overview', path: '/dashboard' },
  { label: 'Tenants', path: '/tenants' },
  // { label: 'Users', path: '/users' },
  // { label: 'Roles', path: '/roles' },
  { label: 'Modules', path: '/modules' },
  { label: 'Audit Logs', path: '/audit-logs' },
];

export const PageHeader = ({
  title,
  description,
  tabs = defaultTabs,
}: PageHeaderProps): ReactElement => {
  const location = useLocation();
  const { roles } = useAppSelector((state) => state.auth);

  // Check if user is super_admin
  let rolesArray: string[] = [];
  if (Array.isArray(roles)) {
    rolesArray = roles;
  } else if (typeof roles === 'string') {
    try {
      rolesArray = JSON.parse(roles);
    } catch {
      rolesArray = [];
    }
  }
  const isSuperAdmin = rolesArray.includes('super_admin');

  const isActiveTab = (path: string): boolean => {
    // Exact match for dashboard
    if (path === '/dashboard') {
      return location.pathname === '/dashboard';
    }
    // For other paths, check if current path starts with the tab path
    return location.pathname.startsWith(path);
  };

  return (
    <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-4 md:gap-6 mb-6">
      {/* Title and Description */}
      <div className="flex flex-col gap-1 max-w-full md:max-w-[434px]">
        <h1 className="text-xl md:text-2xl font-bold text-[#0f1724] tracking-[-0.48px]">
          {title}
        </h1>
        {description && (
          <p className="text-sm font-normal text-[#6b7280]">
            {description}
          </p>
        )}
      </div>

      {/* Tabs Navigation - Only show for super_admin */}
      {isSuperAdmin && tabs.length > 0 && (
        <div className="border border-[rgba(0,0,0,0.2)] rounded-md p-1.5 flex gap-2 overflow-x-auto">
          {tabs.map((tab) => {
            const isActive = isActiveTab(tab.path);
            return (
              <Link
                key={tab.path}
                to={tab.path}
                className={cn(
                  'flex items-center justify-center px-3 py-1.5 rounded text-xs font-medium whitespace-nowrap transition-colors min-w-[76px]',
                  isActive
                    ? 'bg-[#112868] text-white'
                    : 'bg-[#f5f7fa] border border-[rgba(0,0,0,0.08)] text-[#0f1724] hover:bg-gray-100'
                )}
              >
                {tab.label}
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
};
