'use client';

/* eslint jsx-a11y/click-events-have-key-events: warn */

/* eslint jsx-a11y/no-static-element-interactions: warn */
import clsx from 'clsx';
import { observer } from 'mobx-react-lite';
import { usePathname } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { twMerge } from 'tailwind-merge';

import { useStores } from '@/app/(root)/AppProviders';
import NotificationList from '@/components/notification/listView/NotificationList';
import logWebUserEvent from '@/logging/logWebUserEvent';

import ActivityFeedList from '../feed/ActivityFeedList';

export type Props = React.HTMLAttributes<HTMLDivElement> & {
  isOpen: boolean;
  onClose: () => void;
};

const SideSubNav: React.FC<
  React.HTMLAttributes<HTMLDivElement> & {
    isOpen?: boolean;
    onClickOutside?: React.MouseEventHandler;
  }
> = observer((props) => {
  const { children, className, isOpen, onClickOutside, ...restProps } = props;

  return (
    <div
      className={clsx(
        'fixed inset-y-0 right-0 overflow-hidden',
        'z-[1000]',
        'left-(--sidebar-width,200px)',
        {
          'pointer-events-all': isOpen,
          'pointer-events-none': !isOpen,
        }
      )}
      aria-hidden={!isOpen}
      inert={!isOpen}
    >
      <div
        className={clsx(
          'absolute inset-0 bg-black/10 bg-linear-to-r from-black transition-opacity duration-300',
          {
            'opacity-100': isOpen,
            'opacity-0': !isOpen,
          }
        )}
        onClick={onClickOutside}
      />
      <div
        className={twMerge(
          clsx(
            'inset-0 overflow-y-auto',
            'transition-transform duration-300 ease-in-out',
            'bg-background-primary text-foreground-primary',
            {
              'translate-x-0': isOpen,
              '-translate-x-full': !isOpen,
            }
          ),
          className
        )}
        {...restProps}
      >
        {children}
      </div>
    </div>
  );
});

const SideSubNavContent: React.FC<Props> = observer((props) => {
  const { className, isOpen, onClose, ...restProps } = props;

  const { notifications: notificationsStore } = useStores();

  const pathname = usePathname();
  const [selectedTab, setSelectedTab] = useState<'notifications' | 'activity'>(
    'notifications'
  );

  // Close notifications panel and log when we navigate away
  const isOpenRef = useRef(isOpen);
  useEffect(() => {
    isOpenRef.current = isOpen;
  }, [isOpen]);
  useEffect(() => {
    if (isOpenRef.current) {
      onClose();
      logWebUserEvent({
        actionName: 'NotificationListClosed',
        context: {
          unreadCount: notificationsStore.unreadCount,
          isMobile: false,
        },
      });
    }
  }, [pathname]);

  return (
    <SideSubNav
      className={twMerge(
        'h-full w-1/2 max-w-[500px] min-w-[350px] pb-4',
        className
      )}
      {...restProps}
      isOpen={isOpen}
      onClickOutside={(e) => {
        // Do not mark as read if holding shift key
        if (!e.shiftKey) {
          notificationsStore.markAllAsRead();
        }
        onClose();
        logWebUserEvent({
          actionName: 'NotificationListClosed',
          context: {
            unreadCount: notificationsStore.unreadCount,
            isMobile: false,
          },
        });
      }}
    >
      <div className='sticky top-0 z-1 mb-2 flex items-center justify-center bg-background-secondary'>
        <div
          className={clsx(
            'w-full cursor-pointer border-b-2 p-4 text-center duration-300 ease-linear',
            {
              'border-border-secondary': selectedTab !== 'notifications',
            }
          )}
          onClick={() => setSelectedTab('notifications')}
        >
          Notifications
        </div>
        <div
          className={clsx(
            'w-full cursor-pointer border-b-2 p-4 text-center duration-300 ease-linear',
            {
              'border-border-secondary': selectedTab !== 'activity',
            }
          )}
          onClick={() => setSelectedTab('activity')}
        >
          Activity
        </div>
      </div>

      {selectedTab === 'notifications' ? (
        <NotificationList
          currentTime={notificationsStore.notifiedAt}
          notifications={notificationsStore.allNotifications}
          isLoading={notificationsStore.isLoading}
          hasMore={notificationsStore.hasMore}
          onLoadMore={() => notificationsStore.loadMoreNotifications()}
          onDotClick={(payload) => {
            notificationsStore.markAsRead(payload.id);
            logWebUserEvent({
              actionName: 'NotificationItemClicked',
              context: {
                notificationId: payload.id,
                notificationType: payload.type || 'unknown',
                clickTarget: 'dot',
                isRead: false,
                isMobile: false,
              },
            });
          }}
          onProfileClick={(payload, e) => {
            // Do not mark as read if opening in new window
            if (!e || !(e.shiftKey || e.ctrlKey || e.metaKey)) {
              notificationsStore.markAsRead(payload.id);
              onClose();
            }
            logWebUserEvent({
              actionName: 'NotificationItemClicked',
              context: {
                notificationId: payload.id,
                notificationType: payload.type || 'unknown',
                clickTarget: payload.context || 'unknown',
                isRead: payload.isRead,
                isMobile: false,
              },
            });
          }}
          onContentClick={(payload, e) => {
            // Do not mark as read if opening in new window
            if (!e || !(e.shiftKey || e.ctrlKey || e.metaKey)) {
              notificationsStore.markAsRead(payload.id);
              onClose();
            }
            logWebUserEvent({
              actionName: 'NotificationItemClicked',
              context: {
                notificationId: payload.id,
                notificationType: payload.type || 'unknown',
                clickTarget: 'content',
                contentId: payload.contentId,
                contentType: payload.contentType,
                isRead: payload.isRead,
                isMobile: false,
              },
            });
          }}
          onFollowClick={(payload, e) => {
            // Do not mark as read if holding shift key
            if (!e || !e.shiftKey) {
              notificationsStore.markAsRead(payload.id);
            }
            notificationsStore.setFollowing(
              payload.handle,
              !payload.isFollowing
            );
            logWebUserEvent({
              actionName: 'NotificationItemClicked',
              context: {
                notificationId: payload.id,
                notificationType: payload.type || 'unknown',
                clickTarget: payload.isFollowing
                  ? 'unfollow_button'
                  : 'follow_button',
                isRead: payload.isRead,
                isMobile: false,
              },
            });
          }}
          onNotificationView={(payload) => {
            logWebUserEvent({
              actionName: 'NotificationItemViewed',
              context: {
                notificationId: payload.id,
                notificationType: payload.type || 'unknown',
                isRead: payload.isRead,
                isMobile: false,
              },
            });
          }}
        />
      ) : (
        <ActivityFeedList showFullFeed={true} />
      )}
    </SideSubNav>
  );
});

export default SideSubNavContent;
