'use client';

import React, { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname, useRouter } from 'next/navigation';
import { cn } from '@/lib/utils';
import { 
  Home, Bell, Lightbulb, Bookmark, Users, UserPlus, 
  Ban, ChevronLeft, ChevronRight, Sparkles, Zap, Menu, X ,Headset
} from 'lucide-react';
import { ThemeToggle } from '@/components/theme-toggle';
import { useDispatch, useSelector } from 'react-redux';
import axios from 'axios';
import { setSelectedCategory, triggerPostsRefresh } from '@/lib/store/slices/userSlice';

const navItems = [
  { icon: Home, label: 'Home', href: '/home', active: true },
  { icon: Bell, label: 'Notifications', href: '/notifications', badge: 3 },
  { icon: Lightbulb, label: 'My Ideas', href: '/my-idea' },
  { icon: Bookmark, label: 'Saved', href: '/saved' },
  { icon: Users, label: 'Collaborators', href: '/collaborators', isNew: true },
  { icon: UserPlus, label: 'Invite Friends', href: '/invite' },
    { icon: Headset, label: 'Support Us', href: '/support-us' }, 

  { icon: Ban, label: 'Blocked', href: '/blocked' },
];

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
const SECURITY_KEY = process.env.NEXT_PUBLIC_SECURITY_KEY;

export function Sidebar() {
  const dispatch = useDispatch();
  const router = useRouter();
  const pathname = usePathname();
  const [collapsed, setCollapsed] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);
  
  // Get dynamic images from Redux store
  const dynamicImages = useSelector((state: any) => state.user?.dynamicImages);
  const currentCustomer = useSelector((state: any) => state.user?.currentCustomer);
  const accessToken = useSelector((state: any) => state.user?.accessToken);

  // Fetch notification count
  const fetchNotificationCount = useCallback(async () => {
    if (!accessToken) return;
    
    try {
      const response = await axios.get(
        `${BASE_URL}/notification/customerNotificationCount`,
        {
          headers: {
            "x-security-key": SECURITY_KEY,
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );

      if (response.data.success) {
        setUnreadCount(response.data.data || 0);
      }
    } catch (error) {
      console.error("Error fetching notification count:", error);
    }
  }, [accessToken]);

  // Handle home click - reset category and refresh feed only (no page reload)
  const handleHomeClick = (e: React.MouseEvent) => {
    // Agar already home page pe hain
    if (pathname === '/home') {
      e.preventDefault();
      // Reset selected category
      dispatch(setSelectedCategory(null));
      // Trigger posts refresh - feed will reload without page reload
      dispatch(triggerPostsRefresh());
    } else {
      // Agar home page pe nahi hain, toh navigate karo
      router.push('/home');
      // Reset category after navigation
      setTimeout(() => {
        dispatch(setSelectedCategory(null));
        dispatch(triggerPostsRefresh());
      }, 100);
    }
  };

  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth >= 1024) {
        setMobileOpen(false);
      }
    };
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // Fetch notification count on mount and set interval
  // useEffect(() => {
  //   if (accessToken) {
  //     fetchNotificationCount();
  //     const interval = setInterval(fetchNotificationCount, 30000);
  //     return () => clearInterval(interval);
  //   }
  // }, [accessToken, fetchNotificationCount]);

  return (
    <React.Fragment>
      <button
        onClick={() => setMobileOpen(true)}
        className="fixed left-4 top-6 z-50 flex h-11 w-11 items-center justify-center rounded-xl glass glass-border lg:hidden"
      >
        <Menu className="h-5 w-5 text-foreground" />
      </button>

      {mobileOpen && (
        <div
          className="fixed inset-0 z-40 bg-background/80 backdrop-blur-sm lg:hidden"
          onClick={() => setMobileOpen(false)}
        />
      )}

      <aside
        className={cn(
          'fixed left-0  top-0 z-50 flex h-screen flex-col glass glass-border transition-all duration-300',
          collapsed ? 'lg:w-20' : 'lg:w-72',
          mobileOpen ? 'w-72 translate-x-0' : '-translate-x-full lg:translate-x-0'
        )}
      >
        {/* ========== LOGO SECTION - BIGGER LOGO ========== */}
        <div className="flex h-24 items-center justify-between px-4 border-b border-border/50">
          <Link 
            href="/" 
            className="flex items-center gap-3"
            onClick={(e) => {
              e.preventDefault();
              router.push('/home');
              setTimeout(() => {
                dispatch(setSelectedCategory(null));
                dispatch(triggerPostsRefresh());
              }, 100);
            }}
          >
            <div className="relative">
              <div className="absolute inset-0 rounded-xl" />
              <div className="relative flex h-14 w-14 items-center justify-center rounded-xl">
                {/* ✅ DYNAMIC LOGO FROM API - BIGGER SIZE */}
                {dynamicImages?.headerLogo ? (
                  <Image
                    src={`${BASE_URL}/${dynamicImages.headerLogo}`}
                    alt={dynamicImages?.title || "CheckUrIdea"}
                    width={56}
                    height={56}
                    className="h-12 w-auto object-contain"
                    priority
                  />
                ) : (
                  <Zap className="h-7 w-7" />
                )}
              </div>
            </div>
            {!collapsed && (
              <div className="flex flex-col">
                <span className="text-xl font-bold text-gradient">
                  {dynamicImages?.title || 'CheckUrIdea'}
                </span>
                <span className="text-[11px] text-muted-foreground uppercase tracking-wider">
                  Innovate Together
                </span>
              </div>
            )}
          </Link>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setMobileOpen(false)}
              className="flex h-8 w-8 items-center justify-center rounded-lg bg-secondary/50 text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors lg:hidden"
            >
              <X className="h-4 w-4" />
            </button>
            <button
              onClick={() => setCollapsed(!collapsed)}
              className="hidden lg:flex cursor-pointer h-8 w-8 items-center justify-center rounded-lg bg-secondary/50 text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
            >
              {collapsed ? <ChevronRight className="h-4 w-4" /> : <ChevronLeft className="h-4 w-4" />}
            </button>
          </div>
        </div>

        {/* REST ALL SAME - NO CHANGES */}
        {!collapsed && (
          <div className="mx-4 mt-6 rounded-2xl gradient-border p-4 relative overflow-hidden">
            <div className="absolute -right-6 -top-6 h-24 w-24 rounded-full bg-primary/20 blur-2xl" />
            <div className="absolute -bottom-4 -left-4 h-16 w-16 rounded-full bg-accent/20 blur-2xl" />
            <div className="relative">
              <div className="flex items-center gap-2 mb-2">
                <Sparkles className="h-4 w-4 text-accent" />
                <span className="text-sm font-semibold text-foreground">Think. Post. Grow.</span>
              </div>
              <p className="text-xs text-muted-foreground leading-relaxed">
                Your creativity matters — connect, collaborate, and succeed with the community.
              </p>
            </div>
          </div>
        )}

        <nav className="flex-1 overflow-y-auto px-3 py-6 ">
          <ul className="space-y-.5">
            {navItems.map((item) => (
              <li key={item.label}>
                <Link
                  href={item.href}
                  onClick={item.label === 'Home' ? handleHomeClick : undefined}
                  className={cn(
                    'group flex items-center gap-3 rounded-xl px-4 py-2 my-1 transition-all duration-200',
                    item.active
                      ? 'bg-primary/10 text-primary glow-text-primary'
                      : 'text-muted-foreground hover:bg-secondary/50 hover:text-foreground dark:text-white dark:hover:text-white'
                  )}
                >
                  <div
                    className={cn(
                      'relative flex h-6 w-9 items-center justify-center rounded-lg transition-all',
                      item.active ? '' : ' '
                    )}
                  >
                    {item.active && <div className="absolute inset-0  rounded-lg bg-primary/20 blur-md" />}
                    <item.icon className={cn('relative h-5 w-5', item.active && 'text-primary')} />
                  </div>
                  {!collapsed && <span className="flex-1 font-medium">{item.label}</span>}
                  {!collapsed && item.label === 'Notifications' && unreadCount > 0 && (
                    <span className="flex h-5 min-w-5 items-center justify-center rounded-full bg-accent px-1.5 text-xs font-bold text-accent-foreground">
                      {unreadCount > 99 ? "99+" : unreadCount}
                    </span>
                  )}
                  {!collapsed && item.label !== 'Notifications' && item.badge && (
                    <span className="flex h-5 min-w-5 items-center justify-center rounded-full bg-accent px-1.5 text-xs font-bold text-accent-foreground">
                      {item.badge}
                    </span>
                  )}
                  {!collapsed && item.isNew && (
                    <span className="rounded-full bg-primary/20 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider text-primary">
                      New
                    </span>
                  )}
                </Link>
              </li>
            ))}
          </ul>
        </nav>

        <div className="border-t border-border/50 p-4 space-y-3">
          <div>
            {!collapsed && <p className="text-[10px] cursor-pointer text-muted-foreground uppercase tracking-wider mb-2 px-1">Appearance</p>}
            <ThemeToggle collapsed={collapsed} />
          </div>

          {!collapsed && (
            <div className="rounded-xl bg-secondary/30 p-3 text-center">
              <p className="text-xs text-muted-foreground mb-2">Unlock Premium Features</p>
               <Link href='/upgrade'>
              <button type="button" className="w-full cursor-pointer rounded-lg bg-primary py-2 text-sm font-semibold text-primary-foreground transition-all hover:opacity-90">
                Upgrade Now
              </button>
              </Link>
            </div>
          )}
        </div>
      </aside>
    </React.Fragment>
  );
}