/**
 * Admin Layout Components
 * Core UI components for the admin dashboard layout
 */

"use client";

import React, { useState, useRef, useEffect } from "react";
import { useAdminLayout } from "./context";
import {
  AdminLayoutProps,
  SidebarProps,
  HeaderProps,
  ContentAreaProps,
  NavigationMenuProps,
  BreadcrumbNavigationProps,
  UserMenuProps,
  NotificationsPanelProps,
  SearchBarProps,
  NavigationItem,
  SearchResult,
} from "./types";

// Icons mapping - using simple icon names that can be mapped to actual icons
const iconMap: Record<string, string> = {
  dashboard: "📊",
  sites: "🌐",
  templates: "📄",
  users: "👥",
  settings: "⚙️",
  analytics: "📈",
  search: "🔍",
  notification: "🔔",
  profile: "👤",
  logout: "🚪",
  menu: "☰",
  close: "✕",
  chevron: "❯",
  home: "🏠",
};

// Icon component
function Icon({ name, className = "" }: { name: string; className?: string }) {
  return (
    <span className={`inline-block ${className}`}>{iconMap[name] || "●"}</span>
  );
}

// Main Admin Layout Component
export function AdminLayout({
  children,
  config,
  className = "",
}: AdminLayoutProps) {
  const {
    config: layoutConfig,
    navigation,
    breadcrumbs,
    userMenu,
    notifications,
    search,
    updateConfig,
  } = useAdminLayout();

  const finalConfig = { ...layoutConfig, ...config };

  return (
    <div className={`flex h-screen bg-gray-50 ${className}`}>
      {/* Sidebar */}
      <Sidebar
        navigation={navigation}
        config={finalConfig.sidebar}
        onToggle={() =>
          updateConfig({
            sidebar: {
              ...finalConfig.sidebar,
              isCollapsed: !finalConfig.sidebar.isCollapsed,
            },
          })
        }
      />

      {/* Main Content Area */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {/* Header */}
        <Header
          breadcrumbs={breadcrumbs}
          userMenu={userMenu}
          notifications={notifications}
          search={search}
          config={finalConfig.header}
        />

        {/* Content */}
        <ContentArea config={finalConfig.content}>{children}</ContentArea>
      </div>
    </div>
  );
}

// Sidebar Component
export function Sidebar({
  navigation,
  config,
  onToggle,
  className = "",
}: SidebarProps) {
  const { setActiveNavigation } = useAdminLayout();

  const sidebarWidth = config.isCollapsed
    ? config.collapsedWidth
    : config.width;

  return (
    <aside
      className={`bg-white shadow-lg transition-all duration-300 ease-in-out ${className}`}
      style={{ width: sidebarWidth }}
    >
      {/* Sidebar Header */}
      <div className="h-16 flex items-center justify-between px-4 border-b border-gray-200">
        {!config.isCollapsed && (
          <h1 className="text-xl font-bold text-gray-900">CMS Admin</h1>
        )}
        {config.isCollapsible && (
          <button
            onClick={onToggle}
            className="p-2 rounded-md hover:bg-gray-100 transition-colors"
            aria-label={
              config.isCollapsed ? "사이드바 펼치기" : "사이드바 접기"
            }
          >
            <Icon name="menu" className="text-gray-600" />
          </button>
        )}
      </div>

      {/* Navigation */}
      <nav className="flex-1 overflow-y-auto py-4">
        <NavigationMenu
          groups={navigation}
          onItemClick={(item) => setActiveNavigation(item.id)}
        />
      </nav>
    </aside>
  );
}

// Header Component
export function Header({
  breadcrumbs,
  userMenu,
  notifications,
  search,
  config,
  className = "",
}: HeaderProps) {
  return (
    <header
      className={`bg-white shadow-sm border-b border-gray-200 ${className}`}
      style={{ height: config.height }}
    >
      <div className="h-full flex items-center justify-between px-6">
        {/* Left Section */}
        <div className="flex items-center space-x-4">
          {config.showBreadcrumbs && (
            <BreadcrumbNavigation items={breadcrumbs} />
          )}
        </div>

        {/* Right Section */}
        <div className="flex items-center space-x-4">
          {/* Search Bar */}
          <SearchBar
            config={search}
            onSearch={async (query) => {
              // Mock search implementation
              return [
                {
                  id: "1",
                  title: `Search result for "${query}"`,
                  type: "site" as const,
                  url: `/search?q=${query}`,
                },
              ];
            }}
            onResultClick={(result) => {
              window.location.href = result.url;
            }}
          />

          {/* Notifications */}
          {config.showNotifications && (
            <NotificationsPanel
              config={notifications}
              onMarkAsRead={() => {}}
              onClearAll={() => {}}
            />
          )}

          {/* User Menu */}
          {config.showUserMenu && (
            <UserMenu
              config={userMenu}
              onItemClick={(item) => {
                if (item.onClick) {
                  item.onClick();
                } else if (item.href) {
                  window.location.href = item.href;
                }
              }}
            />
          )}
        </div>
      </div>
    </header>
  );
}

// Content Area Component
export function ContentArea({
  children,
  config,
  className = "",
}: ContentAreaProps) {
  return (
    <main
      className={`flex-1 overflow-auto bg-gray-50 ${className}`}
      style={{
        padding: config.padding,
        maxWidth: config.maxWidth,
        margin: config.centerContent ? "0 auto" : undefined,
      }}
    >
      {children}
    </main>
  );
}

// Navigation Menu Component
export function NavigationMenu({
  groups,
  activeItem,
  onItemClick,
  className = "",
}: NavigationMenuProps) {
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());

  const toggleGroup = (groupId: string) => {
    const newExpanded = new Set(expandedGroups);
    if (newExpanded.has(groupId)) {
      newExpanded.delete(groupId);
    } else {
      newExpanded.add(groupId);
    }
    setExpandedGroups(newExpanded);
  };

  const renderNavigationItem = (item: NavigationItem, level = 0) => {
    const hasChildren = item.children && item.children.length > 0;
    const isActive = item.isActive || item.id === activeItem;
    const isExpanded = item.isExpanded || expandedGroups.has(item.id);

    return (
      <div key={item.id}>
        <button
          onClick={() => {
            if (hasChildren) {
              toggleGroup(item.id);
            } else {
              onItemClick(item);
            }
          }}
          className={`
            w-full flex items-center px-4 py-2 text-left text-sm rounded-md transition-colors
            ${
              isActive
                ? "bg-blue-50 text-blue-700 border-r-2 border-blue-500"
                : "text-gray-700 hover:bg-gray-100"
            }
            ${level > 0 ? "ml-4" : ""}
          `}
          style={{ paddingLeft: `${16 + level * 16}px` }}
        >
          <Icon name={item.icon} className="mr-3" />
          <span className="flex-1">{item.label}</span>
          {item.badge && (
            <span className="ml-2 px-2 py-1 text-xs bg-red-500 text-white rounded-full">
              {item.badge}
            </span>
          )}
          {hasChildren && (
            <Icon
              name="chevron"
              className={`ml-2 transition-transform ${
                isExpanded ? "rotate-90" : ""
              }`}
            />
          )}
        </button>

        {hasChildren && isExpanded && (
          <div className="mt-1">
            {item.children!.map((child) =>
              renderNavigationItem(child, level + 1)
            )}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className={className}>
      {groups.map((group) => (
        <div key={group.id} className="mb-6">
          {group.label && (
            <h3 className="px-4 text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">
              {group.label}
            </h3>
          )}
          <div className="space-y-1">
            {group.items.map((item) => renderNavigationItem(item))}
          </div>
        </div>
      ))}
    </div>
  );
}

// Breadcrumb Navigation Component
export function BreadcrumbNavigation({
  items,
  className = "",
}: BreadcrumbNavigationProps) {
  if (!items.length) return null;

  return (
    <nav className={`flex items-center space-x-2 text-sm ${className}`}>
      {items.map((item, index) => (
        <React.Fragment key={index}>
          {index > 0 && (
            <Icon name="chevron" className="text-gray-400 text-xs" />
          )}
          {item.href && !item.isActive ? (
            <a
              href={item.href}
              className="text-gray-600 hover:text-gray-900 transition-colors"
            >
              {item.label}
            </a>
          ) : (
            <span
              className={
                item.isActive ? "text-gray-900 font-medium" : "text-gray-600"
              }
            >
              {item.label}
            </span>
          )}
        </React.Fragment>
      ))}
    </nav>
  );
}

// User Menu Component
export function UserMenu({
  config,
  onItemClick,
  className = "",
}: UserMenuProps) {
  const [isOpen, setIsOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  return (
    <div ref={menuRef} className={`relative ${className}`}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center p-2 rounded-md hover:bg-gray-100 transition-colors"
      >
        <Icon name="profile" className="text-gray-600" />
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg border border-gray-200 py-1 z-50">
          {config.items.map((item) => (
            <div key={item.id}>
              {item.isDivider ? (
                <hr className="my-1 border-gray-200" />
              ) : (
                <button
                  onClick={() => {
                    onItemClick(item);
                    setIsOpen(false);
                  }}
                  className="w-full flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors"
                >
                  <Icon name={item.icon} className="mr-3" />
                  {item.label}
                </button>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// Notifications Panel Component
export function NotificationsPanel({
  config,
  onMarkAsRead,
  onClearAll,
  className = "",
}: NotificationsPanelProps) {
  const [isOpen, setIsOpen] = useState(false);
  const panelRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        panelRef.current &&
        !panelRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  return (
    <div ref={panelRef} className={`relative ${className}`}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="relative p-2 rounded-md hover:bg-gray-100 transition-colors"
      >
        <Icon name="notification" className="text-gray-600" />
        {config.showBadge && config.unreadCount > 0 && (
          <span className="absolute -top-1 -right-1 h-5 w-5 bg-red-500 text-white text-xs rounded-full flex items-center justify-center">
            {config.unreadCount > 99 ? "99+" : config.unreadCount}
          </span>
        )}
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-80 bg-white rounded-md shadow-lg border border-gray-200 z-50">
          <div className="p-4 border-b border-gray-200">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-medium">알림</h3>
              {config.items.length > 0 && (
                <button
                  onClick={() => {
                    onClearAll();
                    setIsOpen(false);
                  }}
                  className="text-sm text-blue-600 hover:text-blue-800"
                >
                  모두 지우기
                </button>
              )}
            </div>
          </div>

          <div className="max-h-96 overflow-y-auto">
            {config.items.length === 0 ? (
              <div className="p-4 text-center text-gray-500">
                새로운 알림이 없습니다.
              </div>
            ) : (
              config.items.map((notification) => (
                <div
                  key={notification.id}
                  className={`p-4 border-b border-gray-100 hover:bg-gray-50 cursor-pointer ${
                    !notification.isRead ? "bg-blue-50" : ""
                  }`}
                  onClick={() => {
                    if (!notification.isRead) {
                      onMarkAsRead(notification.id);
                    }
                    if (notification.actionUrl) {
                      window.location.href = notification.actionUrl;
                    }
                    setIsOpen(false);
                  }}
                >
                  <div className="flex items-start">
                    <div className="flex-1">
                      <p className="text-sm font-medium text-gray-900">
                        {notification.title}
                      </p>
                      <p className="text-sm text-gray-600 mt-1">
                        {notification.message}
                      </p>
                      <p className="text-xs text-gray-500 mt-2">
                        {notification.timestamp.toLocaleDateString("ko-KR")}
                      </p>
                    </div>
                    {!notification.isRead && (
                      <div className="w-2 h-2 bg-blue-500 rounded-full ml-2 mt-2"></div>
                    )}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}

// Search Bar Component
export function SearchBar({
  config,
  onSearch,
  onResultClick,
  className = "",
}: SearchBarProps) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<SearchResult[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const searchRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        searchRef.current &&
        !searchRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    if (query.length >= config.minQueryLength) {
      const timer = setTimeout(async () => {
        setIsLoading(true);
        try {
          const searchResults = await onSearch(query);
          setResults(searchResults.slice(0, config.maxResults));
        } catch (error) {
          console.error("Search error:", error);
          setResults([]);
        }
        setIsLoading(false);
      }, config.debounceDelay);

      return () => clearTimeout(timer);
    } else {
      setResults([]);
    }
  }, [
    query,
    config.minQueryLength,
    config.maxResults,
    config.debounceDelay,
    onSearch,
  ]);

  return (
    <div ref={searchRef} className={`relative ${className}`}>
      <div className="relative">
        <input
          type="text"
          value={query}
          onChange={(e) => {
            setQuery(e.target.value);
            setIsOpen(true);
          }}
          onFocus={() => setIsOpen(true)}
          placeholder={config.placeholder}
          className="w-64 pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
        />
        <Icon
          name="search"
          className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
        />
      </div>

      {isOpen && (query.length >= config.minQueryLength || isLoading) && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-white rounded-md shadow-lg border border-gray-200 z-50">
          {isLoading ? (
            <div className="p-4 text-center text-gray-500">검색 중...</div>
          ) : results.length === 0 ? (
            <div className="p-4 text-center text-gray-500">
              검색 결과가 없습니다.
            </div>
          ) : (
            <div>
              {results.map((result) => (
                <button
                  key={result.id}
                  onClick={() => {
                    onResultClick(result);
                    setIsOpen(false);
                    setQuery("");
                  }}
                  className="w-full p-3 text-left hover:bg-gray-50 border-b border-gray-100 last:border-b-0"
                >
                  <div className="font-medium text-gray-900">
                    {result.title}
                  </div>
                  {result.description && (
                    <div className="text-sm text-gray-600 mt-1">
                      {result.description}
                    </div>
                  )}
                  <div className="text-xs text-gray-500 mt-1 capitalize">
                    {result.type}
                  </div>
                </button>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
