'use client';

import { useState, Suspense, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import { SEMBLE_TAB_CHANGE_EVENT } from '../sembleStats/SembleStatItem';
import {
  Box,
  Container,
  Paper,
  Scroller,
  Tabs,
  TabsList,
  TabsPanel,
} from '@mantine/core';
import TabItem from './TabItem';
import { useFeatureFlags } from '@/lib/clientFeatureFlags';
import useUrlMetadata from '@/features/cards/lib/queries/useUrlMetadata';

import SembleNotesContainer from '../../containers/sembleNotesContainer/SembleNotesContainer';
import SembleNotesContainerSkeleton from '../../containers/sembleNotesContainer/Skeleton.SembleNotesContainer';

import SembleCollectionsContainer from '../../containers/sembleCollectionsContainer/SembleCollectionsContainer';
import SembleCollectionsContainerSkeleton from '../../containers/sembleCollectionsContainer/Skeleton.SembleCollectionsContainer';

import SembleAddedByContainer from '../../containers/sembleAddedByContainer/SembleAddedByContainer';
import SembleAddedByContainerSkeleton from '../../containers/sembleAddedByContainer/Skeleton.SembleAddedByContainer';

import SimilarCardsContainer from '@/features/cards/containers/similarCardsContainer/SimilarCardsContainer';
import SimilarCardsContainerSkeleton from '@/features/cards/containers/similarCardsContainer/Skeleton.SimilarCardsContainer';
import SembleMentionsContainer from '../../containers/sembleMentionsContainer/SembleMentionsContainer';
import SembleMentionsContainerSkeleton from '../../containers/sembleMentionsContainer/Skeleton.SembleMentionsContainer';

import ConnectionsContainer from '@/features/connections/containers/connectionsContainer/ConnectionsContainer';
import ConnectionsContainerSkeleton from '@/features/connections/containers/connectionsContainer/Skeleton.ConnectionsContainer';

import UrlGraphView from '@/features/graph/components/graphView/UrlGraphView';

interface Props {
  url: string;
}

type TabValue =
  | 'notes'
  | 'collections'
  | 'addedBy'
  | 'similar'
  | 'mentions'
  | 'connections'
  | 'graph';

const VALID_TABS: TabValue[] = [
  'notes',
  'collections',
  'addedBy',
  'similar',
  'mentions',
  'connections',
  'graph',
];

export default function SembleTabs(props: Props) {
  const searchParams = useSearchParams();
  const tabParam = searchParams.get('sembleTab') as TabValue;
  const [activeTab, setActiveTab] = useState<TabValue>(
    VALID_TABS.includes(tabParam) ? tabParam : 'similar',
  );
  const { data: featureFlags } = useFeatureFlags();
  const { data: urlMetadata } = useUrlMetadata({
    url: props.url,
    includeStats: true,
  });

  const stats = urlMetadata?.stats;

  useEffect(() => {
    const handler = (event: Event) => {
      const detail = (event as CustomEvent<TabValue>).detail;
      if (VALID_TABS.includes(detail)) {
        setActiveTab(detail);
      }
    };
    window.addEventListener(SEMBLE_TAB_CHANGE_EVENT, handler);
    return () => window.removeEventListener(SEMBLE_TAB_CHANGE_EVENT, handler);
  }, []);

  return (
    <Tabs
      keepMounted={false}
      value={activeTab}
      onChange={(val) => {
        const newTab = val as TabValue;
        setActiveTab(newTab);
        const viaCardId = searchParams.get('viaCardId');
        const qs = `id=${props.url}&sembleTab=${newTab}${viaCardId ? `&viaCardId=${viaCardId}` : ''}`;
        window.history.replaceState(null, '', `?${qs}`);
      }}
    >
      <Box
        style={{
          position: 'sticky',
          top: 55,
          zIndex: 1,
        }}
      >
        <Paper radius={0}>
          <Container px={'xs'} size={'xl'}>
            <TabsList style={{ flexWrap: 'nowrap' }}>
              <Scroller>
                <TabItem value="similar">Similar cards</TabItem>
                <TabItem value="collections" count={stats?.collectionCount}>
                  Collections
                </TabItem>
                <TabItem value="mentions">Mentions</TabItem>
                <TabItem
                  value="connections"
                  count={stats?.connections.all.total}
                >
                  Connections
                </TabItem>
                <TabItem value="notes" count={stats?.noteCount}>
                  Notes
                </TabItem>
                <TabItem value="addedBy" count={stats?.libraryCount}>
                  Added by
                </TabItem>
                {featureFlags?.graphView && (
                  <TabItem value="graph">Graph</TabItem>
                )}
              </Scroller>
            </TabsList>
          </Container>
        </Paper>
      </Box>

      <Container px={'xs'} size={'xl'} mt="md">
        <TabsPanel value="notes">
          <Suspense fallback={<SembleNotesContainerSkeleton />} key={props.url}>
            <SembleNotesContainer url={props.url} />
          </Suspense>
        </TabsPanel>

        <TabsPanel value="collections">
          <Suspense
            fallback={<SembleCollectionsContainerSkeleton />}
            key={props.url}
          >
            <SembleCollectionsContainer url={props.url} />
          </Suspense>
        </TabsPanel>

        <TabsPanel value="addedBy">
          <Suspense
            fallback={<SembleAddedByContainerSkeleton />}
            key={props.url}
          >
            <SembleAddedByContainer url={props.url} />
          </Suspense>
        </TabsPanel>

        <TabsPanel value="similar">
          <Suspense
            fallback={<SimilarCardsContainerSkeleton />}
            key={props.url}
          >
            <SimilarCardsContainer url={props.url} semblePageUrl={props.url} />
          </Suspense>
        </TabsPanel>

        <TabsPanel value="connections">
          <Suspense fallback={<ConnectionsContainerSkeleton />} key={props.url}>
            <ConnectionsContainer url={props.url} />
          </Suspense>
        </TabsPanel>

        {featureFlags?.graphView && (
          <TabsPanel value="graph">
            <UrlGraphView url={props.url} />
          </TabsPanel>
        )}

        <TabsPanel value="mentions">
          <Suspense
            fallback={<SembleMentionsContainerSkeleton />}
            key={props.url}
          >
            <SembleMentionsContainer url={props.url} />
          </Suspense>
        </TabsPanel>
      </Container>
    </Tabs>
  );
}
