import { ReactElement, useState } from 'react';
import { Stack, Typography } from '@mui/joy';
import CollapsibleSection from './CollapsibleSection';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import PageRow from './pagerow/PageRow';
import { Page, PageFilter, PageSortOrder } from '../../../db/pages';
import { StashTag } from '../../../db/constants';
import { filterPages, groupPagesByWindow, sortPages } from '../../sort';

import { InView } from 'react-intersection-observer';
import React from 'react';
import { useAppDispatch, useAppSelector } from '../../../store/hooks';
import { selectSelectedUrls, addMultiToSelection, removeMultiFromSelection, selectSimilarUrls } from '../../../store/uiSlice';
import WindowGroupHeader from '../../components/WindowGroupHeader';
import { selectWindows, selectTabs } from '../../../store/windowsSlice';

interface WindowGroupProps {
  windowId: number;
  pages: Page[];
}

const WindowGroup = React.memo(({ windowId, pages }: WindowGroupProps): ReactElement => {
  const windows = useAppSelector(selectWindows);
  const allTabs = useAppSelector(selectTabs);
  const currentWindow = windows[windowId];
  const windowTabs = currentWindow?.tabIds?.map(id => allTabs[id]).filter(Boolean) || undefined;
  const windowUrls = pages.map((p) => p.nurl.normalized);

  // If windowId is not found or invalid, we show "Archived" or similar.
  // WindowGroupHeader logic handles title default.
  // But we might want to be explicit.
  const title = Number.isNaN(windowId) || !currentWindow ? "Archived / Closed Window" : undefined;
  // Actually, if windowId is defined but not in `windows` (closed), we still might want to show "Window <ID>"?
  // Previous logic: `const windowTitle = Number.isNaN(windowId) ? "Archived" : Window ${windowId};`
  // WindowGroupHeader handles `Window (N pages)` if title missing. 
  // Let's pass explicit title if it's archived.

  // Determine if all pages in this group are stashed
  const allStashed = pages.every(p => p.humanTags && p.humanTags.includes(StashTag));

  return (
    <InView>
      {({ inView, ref, entry }) =>
        inView ? (
          <div
            ref={ref}
            style={{
              border: '1px solid',
              margin: '0.5rem 0.5rem 0.5rem 0.5rem',
              borderColor: 'rgb(50, 56, 62)',
            }}
          >
            <WindowGroupHeader
                urls={windowUrls}
                pageCount={pages.length}
                tabs={windowTabs}
                title={Number.isNaN(windowId) ? "Archived" : undefined}
                allStashed={allStashed}
            />
            <div>
                {pages.map((page) => (
                <PageRow
                    page={page}
                    windowId={windowId}
                    key={page.nurl.normalized}
                />
                ))}
            </div>
          </div>
        ) : (
          <div ref={ref} style={{ height: pages.length * 25 }} />
        )
      }
    </InView>
  );
});

interface RawPageListProps {
  pages: Page[];
  sortOrder: PageSortOrder;
  filter: PageFilter;
  groupByWindow: boolean;
}

const RawPageList = React.memo(({
  pages,
  sortOrder,
  filter,
  groupByWindow,
}: RawPageListProps): ReactElement => {
  var windowsOrPages: JSX.Element[];

  const similarUrls = useAppSelector(selectSimilarUrls);

  // console.log('RawPageList render', { pagesLength: pages?.length, groupByWindow });

  if (groupByWindow) {
    const windowGroupsSorted = groupPagesByWindow(filterPages(pages, filter));
    windowsOrPages = windowGroupsSorted.map(([windowId, windowPages]) => (
      <WindowGroup
        key={windowId}
        windowId={Number(windowId)}
        pages={windowPages}
      />
    ));
  } else {
    const filteredPages = filterPages(pages, filter);
    const pagesSorted = sortPages(filteredPages, sortOrder, similarUrls);
    windowsOrPages = pagesSorted.map((page) => (
      <PageRow page={page} key={page.nurl.normalized} />
    ));
  }

  return <>{windowsOrPages}</>;
});

export default RawPageList;
