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';

const HeaderContainer = styled.header`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding: 1rem 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  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};
`;

const Logo = styled.div`
  font-size: 1.5rem;
  font-weight: 700;
  color: ${({ theme }) => theme.colors.text};
  cursor: pointer;
  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%;
  background: ${({ theme }) => theme.colors.cardBackground};
  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 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;
}

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

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

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

  return (
    <HeaderContainer>
      <Logo onClick={() => navigate('/')}>
        <h4>Hesychia</h4>

      </Logo>

      {/* Desktop Nav */}
      <Nav>
        <NavLink onClick={() => navigate('/')}>Dashboard</NavLink>
        <NavLink onClick={() => navigate('/account/')}>Account</NavLink>
        <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>
        <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;