import { useState, useEffect, useCallback } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Typography, Space, Tooltip, Badge, theme } from 'antd';
import {
  HomeOutlined,
  ThunderboltOutlined,
  VideoCameraOutlined,
  PictureOutlined,
  StarOutlined,
  PlayCircleOutlined,
  TeamOutlined,
  UserOutlined,
  SettingOutlined,
  LoginOutlined,
  LogoutOutlined,
  BarChartOutlined,
  MessageOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DownOutlined,
  RightOutlined,
  ArrowLeftOutlined,
} from '@ant-design/icons';
import { useAuthStore } from '@/stores/auth.store';
import { hexToRgba } from '@/utils/color';
import { mediaApi } from '@/lib/media-api';
import { buildHomeUrl } from '@/lib/service-url';

const { Text } = Typography;

interface NavItem {
  key: string;
  label: string;
  icon: React.ReactNode;
  path: string;
}

interface ChatThread {
  mediaId: number;
  videoTitle: string;
  unreadCount: number;
  lastMessage: {
    content: string;
    userName: string;
    createdAt: string;
  } | null;
}

interface SectionState {
  content: boolean;
  activity: boolean;
  online: boolean;
  account: boolean;
}

export default function MediaSidebar() {
  const navigate = useNavigate();
  const location = useLocation();
  const { token } = theme.useToken();

  // Only hydrate auth if tokens exist (prevents 401 errors on public pages)
  const user = useAuthStore((state) => state.user);
  const logout = useAuthStore((state) => state.logout);
  const hydrate = useAuthStore((state) => state.hydrate);

  useEffect(() => {
    // Check if auth data exists before attempting to hydrate
    const authData = localStorage.getItem('cml-auth');
    if (authData) {
      hydrate();
    }
  }, [hydrate]);

  // Sidebar collapse state (persisted in localStorage)
  const [collapsed, setCollapsed] = useState(() => {
    const saved = localStorage.getItem('media_sidebar_collapsed');
    return saved ? JSON.parse(saved) : false;
  });

  // Section collapse states (persisted in localStorage)
  const [sections, setSections] = useState<SectionState>(() => {
    const saved = localStorage.getItem('media_sidebar_sections');
    return saved
      ? JSON.parse(saved)
      : { content: true, activity: true, online: true, account: true };
  });

  // Chat threads state
  const [chatThreads, setChatThreads] = useState<ChatThread[]>([]);

  const fetchChatThreads = useCallback(async () => {
    if (!user) return;
    try {
      const { data } = await mediaApi.get('/media/chat/threads', { params: { limit: '5' } });
      setChatThreads(data.threads || []);
    } catch {
      // Silent fail for sidebar data
    }
  }, [user]);

  // Fetch chat threads periodically when user is logged in
  useEffect(() => {
    if (user) {
      fetchChatThreads();
      const interval = setInterval(fetchChatThreads, 30000); // Refresh every 30s
      return () => clearInterval(interval);
    } else {
      setChatThreads([]);
    }
  }, [user, fetchChatThreads]);

  // Save collapse state to localStorage
  useEffect(() => {
    localStorage.setItem('media_sidebar_collapsed', JSON.stringify(collapsed));
  }, [collapsed]);

  useEffect(() => {
    localStorage.setItem('media_sidebar_sections', JSON.stringify(sections));
  }, [sections]);

  // Derived hover colors
  const hoverBg = hexToRgba(token.colorPrimary, 0.1);
  const userInfoBg = hexToRgba(token.colorPrimary, 0.05);

  // Navigation items
  const navItems: NavItem[] = [
    { key: 'all', label: 'All', icon: <HomeOutlined />, path: '/gallery' },
    { key: 'shorts', label: 'Shorts', icon: <ThunderboltOutlined />, path: '/gallery/shorts' },
    { key: 'videos', label: 'Videos', icon: <VideoCameraOutlined />, path: '/gallery/videos' },
    { key: 'photos', label: 'Photos', icon: <PictureOutlined />, path: '/gallery/photos' },
    { key: 'curated', label: 'Curated', icon: <StarOutlined />, path: '/gallery/curated' },
    { key: 'playback', label: 'Playback', icon: <PlayCircleOutlined />, path: '/gallery/playback' },
  ];

  // Determine active nav item from current path (longest match wins)
  const getActiveKey = () => {
    const path = location.pathname;
    if (path === '/gallery') return 'all';
    const match = [...navItems]
      .sort((a, b) => b.path.length - a.path.length)
      .find((item) => path.startsWith(item.path));
    return match ? match.key : 'all';
  };

  const activeKey = getActiveKey();

  // Toggle section collapse
  const toggleSection = (section: keyof SectionState) => {
    setSections((prev) => ({ ...prev, [section]: !prev[section] }));
  };

  // Handle navigation
  const handleNavigate = (path: string) => {
    navigate(path);
  };

  // Handle logout
  const handleLogout = async () => {
    await logout();
    navigate('/gallery');
  };

  // Sidebar width
  const sidebarWidth = collapsed ? 64 : 256;

  return (
    <div
      style={{
        width: sidebarWidth,
        height: 'calc(100vh - 56px)',
        background: token.colorBgContainer,
        borderRight: '1px solid rgba(255,255,255,0.06)',
        display: 'flex',
        flexDirection: 'column',
        transition: 'width 0.3s ease',
        overflow: 'hidden',
        position: 'fixed',
        left: 0,
        top: 56,
        zIndex: 100,
      }}
    >
      {/* Header */}
      <div
        style={{
          padding: collapsed ? '16px 8px' : '16px',
          borderBottom: '1px solid rgba(255,255,255,0.06)',
          textAlign: collapsed ? 'center' : 'left',
        }}
      >
        {!collapsed && (
          <Space direction="vertical" size={4} style={{ width: '100%' }}>
            <Text
              strong
              style={{
                fontSize: 18,
                color: token.colorPrimary,
                letterSpacing: '0.5px',
              }}
            >
              Media Gallery
            </Text>
            <Text
              type="secondary"
              style={{
                fontSize: 12,
                color: 'rgba(255,255,255,0.45)',
              }}
            >
              Media Platform
            </Text>
          </Space>
        )}
        {collapsed && (
          <PlayCircleOutlined
            style={{
              fontSize: 24,
              color: token.colorPrimary,
            }}
          />
        )}
      </div>

      {/* Scrollable content */}
      <div
        style={{
          flex: 1,
          overflowY: 'auto',
          overflowX: 'hidden',
        }}
      >
        {/* Home + Back to Site links */}
        <div style={{ padding: collapsed ? '8px 0' : '8px 12px', borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
          <Tooltip title={collapsed ? 'Home' : ''} placement="right">
            <a
              href={buildHomeUrl()}
              target="_blank"
              rel="noopener noreferrer"
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 10,
                padding: collapsed ? '8px 0' : '8px 12px',
                cursor: 'pointer',
                borderRadius: 8,
                color: 'rgba(255,255,255,0.65)',
                transition: 'all 0.2s ease',
                justifyContent: collapsed ? 'center' : 'flex-start',
                fontSize: 13,
                textDecoration: 'none',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.background = hoverBg; e.currentTarget.style.color = 'rgba(255,255,255,0.85)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'rgba(255,255,255,0.65)'; }}
            >
              <HomeOutlined style={{ fontSize: 14 }} />
              {!collapsed && <Text style={{ fontSize: 13, color: 'inherit' }}>Home</Text>}
            </a>
          </Tooltip>
          <Tooltip title={collapsed ? 'Back to Site' : ''} placement="right">
            <div
              onClick={() => navigate('/campaigns')}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 10,
                padding: collapsed ? '8px 0' : '8px 12px',
                cursor: 'pointer',
                borderRadius: 8,
                color: 'rgba(255,255,255,0.65)',
                transition: 'all 0.2s ease',
                justifyContent: collapsed ? 'center' : 'flex-start',
                fontSize: 13,
              }}
              onMouseEnter={(e) => { e.currentTarget.style.background = hoverBg; e.currentTarget.style.color = 'rgba(255,255,255,0.85)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'rgba(255,255,255,0.65)'; }}
            >
              <ArrowLeftOutlined style={{ fontSize: 14 }} />
              {!collapsed && <Text style={{ fontSize: 13, color: 'inherit' }}>Back to Site</Text>}
            </div>
          </Tooltip>
        </div>

        {/* Content Navigation Section */}
        <div style={{ padding: collapsed ? '12px 0' : '12px' }}>
          {/* Section header */}
          {!collapsed && (
            <div
              onClick={() => toggleSection('content')}
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: '8px 12px',
                cursor: 'pointer',
                userSelect: 'none',
              }}
            >
              <Text
                strong
                style={{
                  fontSize: 11,
                  color: 'rgba(255,255,255,0.45)',
                  letterSpacing: '1px',
                }}
              >
                CONTENT
              </Text>
              {sections.content ? (
                <DownOutlined style={{ fontSize: 10, color: 'rgba(255,255,255,0.45)' }} />
              ) : (
                <RightOutlined style={{ fontSize: 10, color: 'rgba(255,255,255,0.45)' }} />
              )}
            </div>
          )}

          {/* Nav items */}
          {sections.content && (
            <div style={{ marginTop: collapsed ? 0 : 8 }}>
              {navItems.map((item) => {
                const isActive = activeKey === item.key;
                return (
                  <Tooltip
                    key={item.key}
                    title={collapsed ? item.label : ''}
                    placement="right"
                  >
                    <div
                      onClick={() => handleNavigate(item.path)}
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: 12,
                        padding: collapsed ? '12px 0' : '12px 16px',
                        margin: collapsed ? '4px 0' : '2px 0',
                        cursor: 'pointer',
                        background: isActive ? token.colorPrimary : 'transparent',
                        borderRadius: collapsed ? 0 : 8,
                        color: isActive
                          ? '#fff'
                          : 'rgba(255,255,255,0.85)',
                        transition: 'all 0.2s ease',
                        justifyContent: collapsed ? 'center' : 'flex-start',
                      }}
                      onMouseEnter={(e) => {
                        if (!isActive) {
                          e.currentTarget.style.background = hoverBg;
                        }
                      }}
                      onMouseLeave={(e) => {
                        if (!isActive) {
                          e.currentTarget.style.background = 'transparent';
                        }
                      }}
                    >
                      <span style={{ fontSize: 18 }}>{item.icon}</span>
                      {!collapsed && (
                        <Text
                          style={{
                            fontSize: 14,
                            color: 'inherit',
                            fontWeight: isActive ? 500 : 400,
                          }}
                        >
                          {item.label}
                        </Text>
                      )}
                    </div>
                  </Tooltip>
                );
              })}
            </div>
          )}
        </div>

        {/* Activity Section */}
        {!collapsed && (
          <div style={{ padding: '12px', borderTop: '1px solid rgba(255,255,255,0.06)' }}>
            <div
              onClick={() => toggleSection('activity')}
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: '8px 12px',
                cursor: 'pointer',
                userSelect: 'none',
              }}
            >
              <Text
                strong
                style={{
                  fontSize: 11,
                  color: 'rgba(255,255,255,0.45)',
                  letterSpacing: '1px',
                }}
              >
                MY CHATS
              </Text>
              {sections.activity ? (
                <DownOutlined style={{ fontSize: 10, color: 'rgba(255,255,255,0.45)' }} />
              ) : (
                <RightOutlined style={{ fontSize: 10, color: 'rgba(255,255,255,0.45)' }} />
              )}
            </div>

            {sections.activity && (
              <div
                style={{
                  marginTop: 8,
                  maxHeight: 200,
                  overflowY: 'auto',
                }}
              >
                {chatThreads.length === 0 ? (
                  <div style={{ padding: '12px 16px' }}>
                    <Text
                      type="secondary"
                      style={{
                        fontSize: 12,
                        color: 'rgba(255,255,255,0.35)',
                      }}
                    >
                      {user ? 'No chat threads yet' : 'Sign in to see chats'}
                    </Text>
                  </div>
                ) : (
                  chatThreads.map((thread) => (
                    <div
                      key={thread.mediaId}
                      onClick={() => navigate(`/gallery/watch/${thread.mediaId}`)}
                      style={{
                        padding: '8px 16px',
                        fontSize: 12,
                        color: 'rgba(255,255,255,0.65)',
                        borderBottom: '1px solid rgba(255,255,255,0.03)',
                        cursor: 'pointer',
                        transition: 'background 0.2s',
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.background = hoverBg;
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.background = 'transparent';
                      }}
                    >
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                        <MessageOutlined style={{ fontSize: 12, color: token.colorPrimary }} />
                        <Text
                          ellipsis
                          style={{
                            fontSize: 12,
                            color: 'rgba(255,255,255,0.85)',
                            fontWeight: thread.unreadCount > 0 ? 600 : 400,
                            flex: 1,
                          }}
                        >
                          {thread.videoTitle}
                        </Text>
                        {thread.unreadCount > 0 && (
                          <Badge count={thread.unreadCount} size="small" />
                        )}
                      </div>
                      {thread.lastMessage && (
                        <Text
                          type="secondary"
                          ellipsis
                          style={{
                            fontSize: 11,
                            color: 'rgba(255,255,255,0.35)',
                            display: 'block',
                            paddingLeft: 18,
                          }}
                        >
                          {thread.lastMessage.userName}: {thread.lastMessage.content}
                        </Text>
                      )}
                    </div>
                  ))
                )}
              </div>
            )}
          </div>
        )}

        {/* Online Section */}
        {!collapsed && (
          <div style={{ padding: '12px', borderTop: '1px solid rgba(255,255,255,0.06)' }}>
            <div
              onClick={() => toggleSection('online')}
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: '8px 12px',
                cursor: 'pointer',
                userSelect: 'none',
              }}
            >
              <Text
                strong
                style={{
                  fontSize: 11,
                  color: 'rgba(255,255,255,0.45)',
                  letterSpacing: '1px',
                }}
              >
                ONLINE
              </Text>
              {sections.online ? (
                <DownOutlined style={{ fontSize: 10, color: 'rgba(255,255,255,0.45)' }} />
              ) : (
                <RightOutlined style={{ fontSize: 10, color: 'rgba(255,255,255,0.45)' }} />
              )}
            </div>

            {sections.online && (
              <div style={{ padding: '12px 16px' }}>
                <Space>
                  <TeamOutlined style={{ color: token.colorPrimary }} />
                  <Text
                    style={{
                      fontSize: 13,
                      color: 'rgba(255,255,255,0.85)',
                    }}
                  >
                    Anonymous viewers
                  </Text>
                </Space>
              </div>
            )}
          </div>
        )}

        {/* Account Section */}
        <div
          style={{
            padding: collapsed ? '12px 0' : '12px',
            borderTop: '1px solid rgba(255,255,255,0.06)',
          }}
        >
          {!collapsed && (
            <div
              onClick={() => toggleSection('account')}
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: '8px 12px',
                cursor: 'pointer',
                userSelect: 'none',
              }}
            >
              <Text
                strong
                style={{
                  fontSize: 11,
                  color: 'rgba(255,255,255,0.45)',
                  letterSpacing: '1px',
                }}
              >
                ACCOUNT
              </Text>
              {sections.account ? (
                <DownOutlined style={{ fontSize: 10, color: 'rgba(255,255,255,0.45)' }} />
              ) : (
                <RightOutlined style={{ fontSize: 10, color: 'rgba(255,255,255,0.45)' }} />
              )}
            </div>
          )}

          {sections.account && (
            <div style={{ marginTop: collapsed ? 0 : 8 }}>
              {user ? (
                <>
                  {/* User info */}
                  {!collapsed && (
                    <div
                      style={{
                        padding: '12px 16px',
                        marginBottom: 8,
                        background: userInfoBg,
                        borderRadius: 8,
                      }}
                    >
                      <Space>
                        <UserOutlined style={{ color: token.colorPrimary }} />
                        <Text
                          style={{
                            fontSize: 13,
                            color: 'rgba(255,255,255,0.85)',
                          }}
                        >
                          {user.email}
                        </Text>
                      </Space>
                    </div>
                  )}

                  {/* My Stats */}
                  {(() => {
                    const isActive = location.pathname === '/gallery/my-stats';
                    return (
                      <Tooltip title={collapsed ? 'My Stats' : ''} placement="right">
                        <div
                          onClick={() => navigate('/gallery/my-stats')}
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: 12,
                            padding: collapsed ? '12px 0' : '12px 16px',
                            margin: collapsed ? '4px 0' : '2px 0',
                            cursor: 'pointer',
                            background: isActive ? token.colorPrimary : 'transparent',
                            borderRadius: collapsed ? 0 : 8,
                            color: isActive ? '#fff' : 'rgba(255,255,255,0.85)',
                            transition: 'all 0.2s ease',
                            justifyContent: collapsed ? 'center' : 'flex-start',
                          }}
                          onMouseEnter={(e) => {
                            if (!isActive) e.currentTarget.style.background = hoverBg;
                          }}
                          onMouseLeave={(e) => {
                            if (!isActive) e.currentTarget.style.background = 'transparent';
                          }}
                        >
                          <BarChartOutlined style={{ fontSize: 18 }} />
                          {!collapsed && <Text style={{ fontSize: 14, color: 'inherit', fontWeight: isActive ? 500 : 400 }}>My Stats</Text>}
                        </div>
                      </Tooltip>
                    );
                  })()}

                  {/* Settings */}
                  {(() => {
                    const isActive = location.pathname === '/gallery/my-settings';
                    return (
                      <Tooltip title={collapsed ? 'Settings' : ''} placement="right">
                        <div
                          onClick={() => navigate('/gallery/my-settings')}
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: 12,
                            padding: collapsed ? '12px 0' : '12px 16px',
                            margin: collapsed ? '4px 0' : '2px 0',
                            cursor: 'pointer',
                            background: isActive ? token.colorPrimary : 'transparent',
                            borderRadius: collapsed ? 0 : 8,
                            color: isActive ? '#fff' : 'rgba(255,255,255,0.85)',
                            transition: 'all 0.2s ease',
                            justifyContent: collapsed ? 'center' : 'flex-start',
                          }}
                          onMouseEnter={(e) => {
                            if (!isActive) e.currentTarget.style.background = hoverBg;
                          }}
                          onMouseLeave={(e) => {
                            if (!isActive) e.currentTarget.style.background = 'transparent';
                          }}
                        >
                          <SettingOutlined style={{ fontSize: 18 }} />
                          {!collapsed && <Text style={{ fontSize: 14, color: 'inherit', fontWeight: isActive ? 500 : 400 }}>Settings</Text>}
                        </div>
                      </Tooltip>
                    );
                  })()}

                  {/* Sign Out */}
                  <Tooltip title={collapsed ? 'Sign Out' : ''} placement="right">
                    <div
                      onClick={handleLogout}
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: 12,
                        padding: collapsed ? '12px 0' : '12px 16px',
                        margin: collapsed ? '4px 0' : '2px 0',
                        cursor: 'pointer',
                        borderRadius: collapsed ? 0 : 8,
                        color: 'rgba(255,255,255,0.85)',
                        transition: 'all 0.2s ease',
                        justifyContent: collapsed ? 'center' : 'flex-start',
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.background = hoverBg;
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.background = 'transparent';
                      }}
                    >
                      <LogoutOutlined style={{ fontSize: 18 }} />
                      {!collapsed && <Text style={{ fontSize: 14, color: 'inherit' }}>Sign Out</Text>}
                    </div>
                  </Tooltip>
                </>
              ) : (
                // Sign In button
                <Tooltip title={collapsed ? 'Sign In' : ''} placement="right">
                  <div
                    onClick={() => navigate('/login')}
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: 12,
                      padding: collapsed ? '12px 0' : '12px 16px',
                      margin: collapsed ? '4px 0' : '2px 0',
                      cursor: 'pointer',
                      borderRadius: collapsed ? 0 : 8,
                      color: token.colorPrimary,
                      transition: 'all 0.2s ease',
                      justifyContent: collapsed ? 'center' : 'flex-start',
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.background = hoverBg;
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.background = 'transparent';
                    }}
                  >
                    <LoginOutlined style={{ fontSize: 18 }} />
                    {!collapsed && <Text style={{ fontSize: 14, color: 'inherit' }}>Sign In</Text>}
                  </div>
                </Tooltip>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Footer with collapse toggle */}
      <div
        style={{
          padding: collapsed ? '12px 0' : '12px 16px',
          borderTop: '1px solid rgba(255,255,255,0.06)',
          textAlign: 'center',
        }}
      >
        {!collapsed && (
          <Text
            type="secondary"
            style={{
              fontSize: 11,
              color: 'rgba(255,255,255,0.35)',
              display: 'block',
              marginBottom: 8,
            }}
          >
            v2.0.0
          </Text>
        )}
        <div
          onClick={() => setCollapsed(!collapsed)}
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '8px',
            cursor: 'pointer',
            borderRadius: 8,
            color: 'rgba(255,255,255,0.65)',
            transition: 'all 0.2s ease',
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.background = hoverBg;
            e.currentTarget.style.color = token.colorPrimary;
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.background = 'transparent';
            e.currentTarget.style.color = 'rgba(255,255,255,0.65)';
          }}
        >
          {collapsed ? (
            <MenuUnfoldOutlined style={{ fontSize: 18 }} />
          ) : (
            <>
              <MenuFoldOutlined style={{ fontSize: 16, marginRight: 8 }} />
              <Text style={{ fontSize: 13, color: 'inherit' }}>Collapse</Text>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
