import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  Home,
  Settings,
  ChevronDown,
  ChevronUp,
  Server,
  Clock,
  Shield,
  Rocket,
  Briefcase,
  Database,
  Container,
  Network,
  Globe,
  GitBranch,
  HardDrive,
  Map,
  Key,
  Layers,
  Boxes,
  FolderTree,
  FileCode,
  Monitor,
  Activity,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useKubeconfigs } from '@/hooks/useKubeconfigs';

export function Sidebar() {
  const navigate = useNavigate();
  const location = useLocation();
  const [clusterExpanded, setClusterExpanded] = useState(false);
  const [workloadsExpanded, setWorkloadsExpanded] = useState(false);
  const [serviceDiscoveryExpanded, setServiceDiscoveryExpanded] =
    useState(false);
  const [storageExpanded, setStorageExpanded] = useState(false);

  // Kubeconfig management
  const { kubeconfigs, activeConfig, setActiveKubeconfig, forceReload } =
    useKubeconfigs();

  // Garantir que dados estão carregados quando sidebar monta
  useEffect(() => {
    console.log(
      '🔍 Sidebar mounted - kubeconfigs length:',
      kubeconfigs.length,
      'activeConfig:',
      activeConfig?.name,
    );
    if (kubeconfigs.length === 0) {
      console.log('🔄 Sidebar: No kubeconfigs found, forcing reload');
      forceReload();
    }
  }, []);

  // Debug: log quando kubeconfigs mudam
  useEffect(() => {
    console.log(
      '📝 Sidebar: kubeconfigs updated:',
      kubeconfigs.length,
      kubeconfigs.map((c) => c.name),
    );
  }, [kubeconfigs]);

  const menuItems = [
    {
      icon: Home,
      label: 'Dashboard',
      path: '/',
      active: location.pathname === '/',
    },
  ];

  const clusterItems = [
    { icon: Boxes, label: 'Nodes', path: '/cluster/nodes' },
    { icon: FolderTree, label: 'Namespaces', path: '/cluster/namespaces' },
  ];

  const workloadItems = [
    { icon: Clock, label: 'CronJobs', path: '/workloads/cronjobs' },
    { icon: Shield, label: 'DaemonSets', path: '/workloads/daemonsets' },
    { icon: Rocket, label: 'Deployments', path: '/workloads/deployments' },
    { icon: Activity, label: 'HPA', path: '/workloads/hpa' },
    { icon: Briefcase, label: 'Jobs', path: '/workloads/jobs' },
    { icon: Container, label: 'Pods', path: '/workloads/pods' },
    { icon: Database, label: 'StatefulSets', path: '/workloads/statefulsets' },
  ];

  const serviceDiscoveryItems = [
    { icon: Globe, label: 'Ingresses', path: '/service-discovery/ingresses' },
    { icon: GitBranch, label: 'Services', path: '/service-discovery/services' },
  ];

  const storageItems = [
    { icon: Map, label: 'ConfigMaps', path: '/storage/configmaps' },
    { icon: Key, label: 'Secrets', path: '/storage/secrets' },
  ];

  const sidebarStyle = {
    backgroundColor: activeConfig?.color || '#3b82f6',
    borderRight: `3px solid ${activeConfig?.color || '#3b82f6'}`,
  };

  // Função para determinar se a cor é clara ou escura
  const isLightColor = (color: string) => {
    const hex = color.replace('#', '');
    const r = parseInt(hex.substr(0, 2), 16);
    const g = parseInt(hex.substr(2, 2), 16);
    const b = parseInt(hex.substr(4, 2), 16);
    const brightness = (r * 299 + g * 587 + b * 114) / 1000;
    return brightness > 128;
  };

  const isLight = isLightColor(activeConfig?.color || '#3b82f6');
  const textColor = isLight ? '#1f2937' : '#ffffff';
  const mutedTextColor = isLight ? '#6b7280' : '#d1d5db';

  return (
    <div className="flex flex-col h-full border-r w-64" style={sidebarStyle}>
      {/* Header */}
      <div className="flex items-center justify-center py-4 px-4">
        <div className="flex items-center space-x-2">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="32"
            height="32"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            style={{ color: textColor }}
          >
            <path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z" />
            <path d="M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12" />
            <path d="M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17" />
          </svg>
          <span className="text-2xl font-bold" style={{ color: textColor }}>
            Kube Now
          </span>
        </div>
      </div>

      <div
        className="h-px w-full"
        style={{ backgroundColor: isLight ? '#e5e7eb' : '#374151' }}
      />

      {/* Navigation */}
      <nav className="flex-1 p-2">
        <ul className="space-y-1">
          {menuItems.map((item, index) => (
            <li key={index}>
              <Button
                variant={item.active ? 'secondary' : 'ghost'}
                className="w-full justify-start px-3"
                onClick={() => navigate(item.path)}
                style={{
                  backgroundColor: item.active
                    ? isLight
                      ? 'rgba(0,0,0,0.1)'
                      : 'rgba(255,255,255,0.1)'
                    : 'transparent',
                  color: textColor,
                  border: 'none',
                }}
              >
                <item.icon
                  className="h-5 w-5 mr-3"
                  style={{ color: textColor }}
                />
                <span className="text-sm" style={{ color: textColor }}>
                  {item.label}
                </span>
              </Button>
            </li>
          ))}

          {/* Cluster Menu */}
          <li>
            <Button
              variant="ghost"
              className="w-full justify-between px-3"
              onClick={() => setClusterExpanded(!clusterExpanded)}
              style={{
                backgroundColor: 'transparent',
                color: textColor,
                border: 'none',
              }}
            >
              <div className="flex items-center">
                <Layers className="h-5 w-5 mr-3" style={{ color: textColor }} />
                <span className="text-sm" style={{ color: textColor }}>
                  Cluster
                </span>
              </div>
              {clusterExpanded ? (
                <ChevronUp className="h-4 w-4" style={{ color: textColor }} />
              ) : (
                <ChevronDown className="h-4 w-4" style={{ color: textColor }} />
              )}
            </Button>
            {/* Submenu */}
            {clusterExpanded && (
              <ul className="ml-6 mt-1 space-y-1">
                {clusterItems.map((item, index) => (
                  <li key={index}>
                    <Button
                      variant={
                        location.pathname === item.path ? 'secondary' : 'ghost'
                      }
                      className="w-full justify-start px-3"
                      onClick={() => navigate(item.path)}
                      style={{
                        backgroundColor:
                          location.pathname === item.path
                            ? isLight
                              ? 'rgba(0,0,0,0.1)'
                              : 'rgba(255,255,255,0.1)'
                            : 'transparent',
                        color: textColor,
                        border: 'none',
                      }}
                    >
                      <item.icon
                        className="h-4 w-4 mr-3"
                        style={{ color: textColor }}
                      />
                      <span className="text-sm" style={{ color: textColor }}>
                        {item.label}
                      </span>
                    </Button>
                  </li>
                ))}
              </ul>
            )}
          </li>

          {/* Workloads Menu */}
          <li>
            <Button
              variant="ghost"
              className="w-full justify-between px-3"
              onClick={() => setWorkloadsExpanded(!workloadsExpanded)}
              style={{
                backgroundColor: 'transparent',
                color: textColor,
                border: 'none',
              }}
            >
              <div className="flex items-center">
                <Server className="h-5 w-5 mr-3" style={{ color: textColor }} />
                <span className="text-sm" style={{ color: textColor }}>
                  Workloads
                </span>
              </div>
              {workloadsExpanded ? (
                <ChevronUp className="h-4 w-4" style={{ color: textColor }} />
              ) : (
                <ChevronDown className="h-4 w-4" style={{ color: textColor }} />
              )}
            </Button>
            {/* Submenu */}
            {workloadsExpanded && (
              <ul className="ml-6 mt-1 space-y-1">
                {workloadItems.map((item, index) => (
                  <li key={index}>
                    <Button
                      variant={
                        location.pathname === item.path ? 'secondary' : 'ghost'
                      }
                      className="w-full justify-start px-3"
                      onClick={() => navigate(item.path)}
                      style={{
                        backgroundColor:
                          location.pathname === item.path
                            ? isLight
                              ? 'rgba(0,0,0,0.1)'
                              : 'rgba(255,255,255,0.1)'
                            : 'transparent',
                        color: textColor,
                        border: 'none',
                      }}
                    >
                      <item.icon
                        className="h-4 w-4 mr-3"
                        style={{ color: textColor }}
                      />
                      <span className="text-sm" style={{ color: textColor }}>
                        {item.label}
                      </span>
                    </Button>
                  </li>
                ))}
              </ul>
            )}
          </li>

          {/* Service Discovery Menu */}
          <li>
            <Button
              variant="ghost"
              className="w-full justify-between px-3"
              onClick={() =>
                setServiceDiscoveryExpanded(!serviceDiscoveryExpanded)
              }
              style={{
                backgroundColor: 'transparent',
                color: textColor,
                border: 'none',
              }}
            >
              <div className="flex items-center">
                <Network
                  className="h-5 w-5 mr-3"
                  style={{ color: textColor }}
                />
                <span className="text-sm" style={{ color: textColor }}>
                  Service Discovery
                </span>
              </div>
              {serviceDiscoveryExpanded ? (
                <ChevronUp className="h-4 w-4" style={{ color: textColor }} />
              ) : (
                <ChevronDown className="h-4 w-4" style={{ color: textColor }} />
              )}
            </Button>
            {/* Submenu */}
            {serviceDiscoveryExpanded && (
              <ul className="ml-6 mt-1 space-y-1">
                {serviceDiscoveryItems.map((item, index) => (
                  <li key={index}>
                    <Button
                      variant={
                        location.pathname === item.path ? 'secondary' : 'ghost'
                      }
                      className="w-full justify-start px-3"
                      onClick={() => navigate(item.path)}
                      style={{
                        backgroundColor:
                          location.pathname === item.path
                            ? isLight
                              ? 'rgba(0,0,0,0.1)'
                              : 'rgba(255,255,255,0.1)'
                            : 'transparent',
                        color: textColor,
                        border: 'none',
                      }}
                    >
                      <item.icon
                        className="h-4 w-4 mr-3"
                        style={{ color: textColor }}
                      />
                      <span className="text-sm" style={{ color: textColor }}>
                        {item.label}
                      </span>
                    </Button>
                  </li>
                ))}
              </ul>
            )}
          </li>

          {/* Storage Menu */}
          <li>
            <Button
              variant="ghost"
              className="w-full justify-between px-3"
              onClick={() => setStorageExpanded(!storageExpanded)}
              style={{
                backgroundColor: 'transparent',
                color: textColor,
                border: 'none',
              }}
            >
              <div className="flex items-center">
                <HardDrive
                  className="h-5 w-5 mr-3"
                  style={{ color: textColor }}
                />
                <span className="text-sm" style={{ color: textColor }}>
                  Storage
                </span>
              </div>
              {storageExpanded ? (
                <ChevronUp className="h-4 w-4" style={{ color: textColor }} />
              ) : (
                <ChevronDown className="h-4 w-4" style={{ color: textColor }} />
              )}
            </Button>
            {/* Submenu */}
            {storageExpanded && (
              <ul className="ml-6 mt-1 space-y-1">
                {storageItems.map((item, index) => (
                  <li key={index}>
                    <Button
                      variant={
                        location.pathname === item.path ? 'secondary' : 'ghost'
                      }
                      className="w-full justify-start px-3"
                      onClick={() => navigate(item.path)}
                      style={{
                        backgroundColor:
                          location.pathname === item.path
                            ? isLight
                              ? 'rgba(0,0,0,0.1)'
                              : 'rgba(255,255,255,0.1)'
                            : 'transparent',
                        color: textColor,
                        border: 'none',
                      }}
                    >
                      <item.icon
                        className="h-4 w-4 mr-3"
                        style={{ color: textColor }}
                      />
                      <span className="text-sm" style={{ color: textColor }}>
                        {item.label}
                      </span>
                    </Button>
                  </li>
                ))}
              </ul>
            )}
          </li>
        </ul>
      </nav>

      {/* Footer - Kubeconfig Selector */}
      <div
        className="p-4"
        style={{
          borderTop: `1px solid ${isLight ? '#e5e7eb' : '#374151'}`,
        }}
      >
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              className="w-full justify-start p-2 h-auto"
              style={{
                backgroundColor: 'transparent',
                color: textColor,
                border: 'none',
              }}
            >
              <div className="flex items-center space-x-3 w-full">
                <Avatar className="h-8 w-8">
                  <AvatarFallback
                    style={{
                      backgroundColor: `${activeConfig?.color || '#3b82f6'}20`,
                      color: activeConfig?.color || '#3b82f6',
                    }}
                  >
                    <FileCode className="h-4 w-4" />
                  </AvatarFallback>
                </Avatar>
                <div className="flex-1 min-w-0 text-left">
                  <p
                    className="text-sm font-medium truncate"
                    style={{ color: textColor }}
                  >
                    {activeConfig?.name || 'Kubeconfig Padrão'}
                  </p>
                  <p
                    className="text-xs truncate"
                    style={{ color: mutedTextColor }}
                  >
                    Configuração do cluster
                  </p>
                </div>
                <ChevronDown
                  className="h-4 w-4"
                  style={{ color: mutedTextColor }}
                />
              </div>
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-64">
            <DropdownMenuLabel className="flex items-center">
              <Monitor className="h-4 w-4 mr-2" />
              Selecionar Kubeconfig
            </DropdownMenuLabel>
            <DropdownMenuSeparator />
            {kubeconfigs.map((config) => (
              <DropdownMenuItem
                key={config.id}
                onClick={() => setActiveKubeconfig(config.id)}
                className="flex items-center justify-between"
              >
                <div className="flex items-center">
                  <FileCode className="h-4 w-4 mr-2" />
                  <div>
                    <div className="font-medium">{config.name}</div>
                    <div className="text-xs text-muted-foreground">
                      {config.path}
                    </div>
                  </div>
                </div>
                {config.isActive && (
                  <div
                    className="w-2 h-2 rounded-full"
                    style={{ backgroundColor: config.color || '#3b82f6' }}
                  />
                )}
              </DropdownMenuItem>
            ))}
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={() => navigate('/settings/kubeconfigs')}>
              <Settings className="h-4 w-4 mr-2" />
              Gerenciar Configurações
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </div>
  );
}
