import React, { forwardRef, useState } from "react";
import { BaseComponentProps, User } from "../../types";
import { Button } from "../ui/Button";

export interface NavigationItem {
  id: string;
  label: string;
  href?: string;
  icon?: React.ReactNode;
  active?: boolean;
  onClick?: () => void;
  children?: NavigationItem[];
}

export interface DashboardLayoutProps extends BaseComponentProps {
  user?: User | null;
  navigation?: NavigationItem[];
  headerContent?: React.ReactNode;
  sidebarHeader?: React.ReactNode;
  showSidebar?: boolean;
  sidebarCollapsed?: boolean;
  onSidebarToggle?: () => void;
  onNavigationClick?: (item: NavigationItem) => void;
  onUserMenuClick?: () => void;
  logoContent?: React.ReactNode;
}

export const DashboardLayout = forwardRef<HTMLDivElement, DashboardLayoutProps>(
  (
    {
      children,
      className = "",
      user,
      navigation = [],
      headerContent,
      sidebarHeader,
      showSidebar = true,
      sidebarCollapsed = false,
      onSidebarToggle,
      onNavigationClick,
      onUserMenuClick,
      logoContent,
      ...props
    },
    ref
  ) => {
    const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

    const handleNavigationClick = (item: NavigationItem) => {
      onNavigationClick?.(item);
      if (item.onClick) {
        item.onClick();
      }
      // Close mobile menu after navigation
      setIsMobileMenuOpen(false);
    };

    const renderNavigationItem = (item: NavigationItem, level = 0) => (
      <li key={item.id} className={`${level > 0 ? "ml-4" : ""}`}>
        <button
          onClick={() => handleNavigationClick(item)}
          className={`
            w-full text-left px-3 py-2 rounded-md text-sm font-medium transition-colors
            ${
              item.active
                ? "bg-primary-100 text-primary-900 dark:bg-primary-900 dark:text-primary-100"
                : "text-gray-600 hover:text-gray-900 hover:bg-gray-50 dark:text-gray-300 dark:hover:text-white dark:hover:bg-gray-700"
            }
            ${sidebarCollapsed ? "justify-center" : "flex items-center"}
          `}
        >
          {item.icon && (
            <span className={`${sidebarCollapsed ? "" : "mr-3"} flex-shrink-0`}>
              {item.icon}
            </span>
          )}
          {!sidebarCollapsed && <span>{item.label}</span>}
        </button>
        {item.children && item.children.length > 0 && !sidebarCollapsed && (
          <ul className="mt-1 space-y-1">
            {item.children.map((child) =>
              renderNavigationItem(child, level + 1)
            )}
          </ul>
        )}
      </li>
    );

    return (
      <div
        ref={ref}
        className={`flex h-screen bg-gray-50 dark:bg-gray-900 ${className}`}
        {...props}
      >
        {/* Sidebar */}
        {showSidebar && (
          <>
            {/* Mobile sidebar overlay */}
            {isMobileMenuOpen && (
              <div
                className="fixed inset-0 z-40 bg-gray-600 bg-opacity-50 lg:hidden"
                onClick={() => setIsMobileMenuOpen(false)}
              />
            )}

            {/* Sidebar */}
            <div
              className={`
                fixed inset-y-0 left-0 z-50 bg-white dark:bg-gray-800 shadow-lg transform transition-transform duration-300 ease-in-out lg:translate-x-0 lg:static lg:inset-0
                ${isMobileMenuOpen ? "translate-x-0" : "-translate-x-full"}
                ${sidebarCollapsed ? "w-16" : "w-64"}
                lg:block
              `}
            >
              <div className="flex flex-col h-full">
                {/* Sidebar Header */}
                <div
                  className={`flex items-center ${
                    sidebarCollapsed ? "justify-center" : "justify-between"
                  } h-16 px-4 border-b border-gray-200 dark:border-gray-700`}
                >
                  {!sidebarCollapsed && (
                    <div className="flex items-center">
                      {logoContent || (
                        <h1 className="text-xl font-semibold text-gray-900 dark:text-white">
                          Dashboard
                        </h1>
                      )}
                    </div>
                  )}
                  {sidebarHeader}
                </div>

                {/* Navigation */}
                <nav className="flex-1 px-2 py-4 space-y-1 overflow-y-auto">
                  <ul className="space-y-1">
                    {navigation.map((item) => renderNavigationItem(item))}
                  </ul>
                </nav>

                {/* User info (if not collapsed) */}
                {!sidebarCollapsed && user && (
                  <div className="border-t border-gray-200 dark:border-gray-700 p-4">
                    <button
                      onClick={onUserMenuClick}
                      className="flex items-center w-full px-3 py-2 text-sm font-medium text-gray-600 rounded-md hover:text-gray-900 hover:bg-gray-50 dark:text-gray-300 dark:hover:text-white dark:hover:bg-gray-700"
                    >
                      {user.avatar_url ? (
                        <img
                          className="w-8 h-8 mr-3 rounded-full"
                          src={user.avatar_url}
                          alt={user.name || "User"}
                        />
                      ) : (
                        <div className="w-8 h-8 mr-3 bg-gray-300 rounded-full flex items-center justify-center">
                          <span className="text-sm font-medium text-gray-700">
                            {user.name?.charAt(0) ||
                              user.email?.charAt(0) ||
                              "U"}
                          </span>
                        </div>
                      )}
                      <div className="text-left">
                        <p className="text-sm font-medium text-gray-900 dark:text-white">
                          {user.name || "User"}
                        </p>
                        <p className="text-xs text-gray-500 dark:text-gray-400">
                          {user.email}
                        </p>
                      </div>
                    </button>
                  </div>
                )}
              </div>
            </div>
          </>
        )}

        {/* Main content */}
        <div className="flex flex-col flex-1 lg:ml-0">
          {/* Header */}
          <header className="bg-white dark:bg-gray-800 shadow-sm border-b border-gray-200 dark:border-gray-700">
            <div className="flex items-center justify-between h-16 px-4 lg:px-6">
              <div className="flex items-center">
                {/* Mobile menu button */}
                {showSidebar && (
                  <Button
                    variant="ghost"
                    size="sm"
                    className="mr-2 lg:hidden"
                    onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
                    ariaLabel="Toggle sidebar"
                  >
                    <svg
                      className="w-6 h-6"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M4 6h16M4 12h16M4 18h16"
                      />
                    </svg>
                  </Button>
                )}

                {/* Desktop sidebar toggle */}
                {showSidebar && onSidebarToggle && (
                  <Button
                    variant="ghost"
                    size="sm"
                    className="mr-2 hidden lg:flex"
                    onClick={onSidebarToggle}
                    ariaLabel="Toggle sidebar"
                  >
                    <svg
                      className="w-6 h-6"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M4 6h16M4 12h16M4 18h16"
                      />
                    </svg>
                  </Button>
                )}
              </div>

              {/* Header content */}
              <div className="flex items-center space-x-4">{headerContent}</div>
            </div>
          </header>

          {/* Main content area */}
          <main className="flex-1 p-4 lg:p-6 overflow-auto">{children}</main>
        </div>
      </div>
    );
  }
);

DashboardLayout.displayName = "DashboardLayout";
