import React, { useContext, useState } from 'react';
import styled, { useTheme } from 'styled-components';
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../../contexts/AuthContext';
import { AccountContext } from '../../contexts/AccountContext';
import { applyAccessToken, axiosInstance } from '../../../axiosApi';
import { clearTokens, getRefreshToken } from '../../auth/tokenStorage';
import { useSubscription } from '../../hooks/useSubscription';
import { logOutRevenueCat } from '../../utils/revenueCat';
import hesychiaMark from '../../assets/brand/hesychia-mark.png';

const HeaderContainer = styled.header`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  padding: 1rem 2rem;
  padding-top: calc(1rem + env(safe-area-inset-top, 0px));
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
  z-index: 100;
  background: ${({ theme }) => theme.darkMode ? 'rgba(0, 0, 0, 0.2)' : 'rgba(255, 255, 255, 0.2)'};
  backdrop-filter: blur(5px);
  border-bottom: 1px solid ${({ theme }) => theme.colors.cardBorder};

  @media (max-width: 768px) {
    padding: 0.75rem 1rem;
    padding-top: calc(0.75rem + env(safe-area-inset-top, 0px));
  }
`;

const BrandCluster = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  min-width: 0;
  flex: 1;
`;

const ConversationsToggle = styled.button`
  display: none;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  gap: 0.35rem;
  margin: 0;
  padding: 0.35rem 0.55rem;
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 0.65rem;
  background: ${({ theme }) =>
    theme.darkMode ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.06)'};
  color: ${({ theme }) => theme.colors.text};
  cursor: pointer;
  transition: background 0.2s ease;

  &:hover {
    background: ${({ theme }) =>
      theme.darkMode ? 'rgba(255, 255, 255, 0.14)' : 'rgba(0, 0, 0, 0.1)'};
  }

  @media (max-width: 768px) {
    display: inline-flex;
  }
`;

const ConversationsToggleLabel = styled.span`
  font-size: 0.8rem;
  font-weight: 600;
  white-space: nowrap;

  @media (max-width: 380px) {
    display: none;
  }
`;

const Logo = styled.div`
  display: flex;
  align-items: center;
  gap: 0.65rem;
  min-width: 0;
  cursor: pointer;
`;

const LogoMark = styled.img`
  width: 2rem;
  height: 2rem;
  flex-shrink: 0;
  display: block;
  border-radius: 50%;
`;

const LogoWordmark = styled.h4`
  margin: 0;
  font-size: 1.5rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 700;

  @media (max-width: 768px) {
    font-size: 1.25rem;
  }
  color: ${({ theme }) => theme.colors.text};
  background: ${({ theme }) => `linear-gradient(135deg, ${theme.main} 0%, ${theme.focus} 100%)`};
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
`;

const Nav = styled.nav`
  display: flex;
  gap: 1.5rem;

  @media (max-width: 768px) {
    display: none;
  }
`;

const NavLink = styled.button`
  background: transparent;
  border: none;
  color: ${({ theme }) => theme.colors.text};
  opacity: 0.7;
  font-size: 0.95rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;

  &:hover {
    opacity: 1;
    background: ${({ theme }) => theme.darkMode ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'};
  }
`;

const SignOutButton = styled(NavLink)`
  color: #ff6b6b;
  opacity: 1;
  
  &:hover {
    color: #ff4757;
    background: rgba(255, 71, 87, 0.1);
  }
`;

const MobileMenuButton = styled.button`
  display: none;
  background: transparent;
  border: none;
  cursor: pointer;
  z-index: 101;

  @media (max-width: 768px) {
    display: block;
  }
`;

const MobileMenuDropdown = styled.div<{ isOpen: boolean }>`
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  background: ${({ theme }) => theme.darkMode ? 'rgba(10, 12, 22, 0.97)' : 'rgba(255, 255, 255, 0.97)'};
  backdrop-filter: blur(10px);
  border-bottom: 1px solid ${({ theme }) => theme.colors.cardBorder};
  display: flex;
  flex-direction: column;
  padding: 1rem;
  gap: 1rem;
  transform: ${({ isOpen }) => (isOpen ? 'translateY(0)' : 'translateY(-20px)')};
  opacity: ${({ isOpen }) => (isOpen ? '1' : '0')};
  pointer-events: ${({ isOpen }) => (isOpen ? 'auto' : 'none')};
  transition: all 0.3s ease;
  z-index: 99;
`;

const HamburgerIcon = ({ color }: { color: string }) => (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M3 12H21" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    <path d="M3 6H21" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    <path d="M3 18H21" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

const ConversationsMenuIcon = ({ color }: { color: string }) => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
    <path d="M3 12H21" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    <path d="M3 6H21" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    <path d="M3 18H21" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

const CloseIcon = ({ color }: { color: string }) => (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M18 6L6 18" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    <path d="M6 6L18 18" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

type Header2Props = {
  absolute?: Boolean;
  light?: Boolean;
  isMini?: Boolean;
  /** Mobile: open conversations drawer. Rendered inline beside logo when set. */
  onOpenConversations?: () => void;
}

const Header2 = ({
  absolute = false,
  light = false,
  isMini = false,
  onOpenConversations,
}: Header2Props): JSX.Element => {
  const { setAuthentication } = useContext(AuthContext);
  const { setAccount } = useContext(AccountContext);
  const navigate = useNavigate();
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const theme = useTheme();
  const { hasRag } = useSubscription();

  const handleSignOut = async () => {
    try {
      await axiosInstance.post('blacklist/', {
        'refresh_token': getRefreshToken()
      })
      await clearTokens();
      applyAccessToken(null);
      setAuthentication(false)
      setAccount(undefined);
      void Promise.resolve(logOutRevenueCat()).catch((err) => console.warn('RevenueCat logOut', err));
      navigate('/signin/')
    } catch (e) {
      console.error(e);
    }
  }

  const handleNavClick = (path: string) => {
    navigate(path);
    setIsMenuOpen(false);
  };

  return (
    <HeaderContainer>
      <BrandCluster>
        {onOpenConversations && (
          <ConversationsToggle
            type="button"
            onClick={onOpenConversations}
            aria-label="Open conversations"
          >
            <ConversationsMenuIcon color={theme.colors.text} />
            <ConversationsToggleLabel>Conversations</ConversationsToggleLabel>
          </ConversationsToggle>
        )}
        <Logo onClick={() => navigate('/')}>
          <LogoMark src={hesychiaMark} alt="" />
          <LogoWordmark>Hesychia</LogoWordmark>
        </Logo>
      </BrandCluster>

      {/* Desktop Nav */}
      <Nav>
        <NavLink onClick={() => navigate('/')}>Dashboard</NavLink>
        <NavLink onClick={() => navigate('/account/')}>Account</NavLink>
        {hasRag && <NavLink onClick={() => navigate('/document_storage/')}>Documents</NavLink>}
        <NavLink onClick={() => navigate('/analytics/')}>Analytics</NavLink>
        <NavLink onClick={() => navigate('/feedback/')}>Feedback</NavLink>
        <SignOutButton onClick={handleSignOut}>Sign Out</SignOutButton>
      </Nav>

      {/* Mobile Menu Button */}
      <MobileMenuButton onClick={() => setIsMenuOpen(!isMenuOpen)}>
        {isMenuOpen ? <CloseIcon color={theme.colors.text} /> : <HamburgerIcon color={theme.colors.text} />}
      </MobileMenuButton>

      {/* Mobile Menu Dropdown */}
      <MobileMenuDropdown isOpen={isMenuOpen}>
        <NavLink onClick={() => handleNavClick('/')}>Dashboard</NavLink>
        <NavLink onClick={() => handleNavClick('/account/')}>Account</NavLink>
        {hasRag && <NavLink onClick={() => handleNavClick('/document_storage/')}>Documents</NavLink>}
        <NavLink onClick={() => handleNavClick('/analytics/')}>Analytics</NavLink>
        <NavLink onClick={() => handleNavClick('/feedback/')}>Feedback</NavLink>
        <SignOutButton onClick={() => { handleSignOut(); setIsMenuOpen(false); }}>Sign Out</SignOutButton>
      </MobileMenuDropdown>
    </HeaderContainer>
  )
}

export default Header2;