import React, { useState } from 'react';
import { AppStateProvider, useDraft, useDraftUsage, useAppStateDispatch } from './Context.js';
import { Tab, TabList, TabPanel, Tabs } from 'react-tabs';
import Keywords from './pages/Keywords.js';
import Competitors from './pages/Competitors.js';
import ContentOutline from './pages/ContentOutline.js';
import Footer from './components/Footer.js';
import DraftUsageAlert from './components/DraftUsageAlert.js';
import './App.css';
import ErrorBoundary from './utilities/ErrorBoundary.js';

function AppInner() {
  const [tabIndex, setTabIndex] = useState(0);
  const { maxDrafts, usedDrafts, alertIsDismissed } = useDraftUsage();
  const dispatch = useAppStateDispatch();
  const draft = useDraft();

  // Calculate if user has run out of drafts
  const hasRunOutOfDrafts = maxDrafts - usedDrafts <= 0;
  // Show tabs if: user has drafts available OR has an existing draft ID
  const shouldShowTabs = !hasRunOutOfDrafts || draft?.id;
  // Show alert if the quota spent is higher than 2/3.
  const shouldShowDraftUsageAlert = usedDrafts / maxDrafts > 0.6 && !alertIsDismissed;

  return (
    <div className="conductor">
      {shouldShowDraftUsageAlert && (
        <DraftUsageAlert
          usedDrafts={usedDrafts}
          maxDrafts={maxDrafts}
          onClick={() =>
            dispatch({
              type: 'setDraftUsageAlertIsDismissed',
              draftUsageAlertIsDismissed: true,
            })
          }
        />
      )}
      {shouldShowTabs ? (
        <Tabs
          className="conductor__tabs"
          selectedIndex={tabIndex}
          onSelect={(index) => setTabIndex(index)}
        >
          <TabList className="conductor__tab-list">
            <Tab className="conductor__tab">Keywords</Tab>
            <Tab className="conductor__tab">Competitors</Tab>
            <Tab className="conductor__tab">Content outline</Tab>
          </TabList>
          <TabPanel className="conductor__tab-panel">
            <Keywords setTab={(index: number) => setTabIndex(index)} nextTab={1} />
          </TabPanel>
          <TabPanel className="conductor__tab-panel">
            <Competitors setTab={(index: number) => setTabIndex(index)} nextTab={2} />
          </TabPanel>
          <TabPanel className="conductor__tab-panel">
            <ContentOutline />
          </TabPanel>
          <Footer />
        </Tabs>
      ) : (
        <div className="conductor__no-drafts-message">
          You have reached your draft limit. Please contact support to increase your limit.
        </div>
      )}
    </div>
  );
}

function App() {
  const [appKey, setAppKey] = useState(0);

  const accountId = window?.drupalSettings?.conductor?.accountId ?? '';
  const draftId = window?.drupalSettings?.conductor?.draftId ?? '';
  const maxDrafts = window?.drupalSettings?.conductor?.maxDrafts ?? 0;
  const usedDrafts = window?.drupalSettings?.conductor?.usedDrafts ?? 0;

  let entityId = 0;
  let entityType = '';
  if (window.location.pathname.startsWith('/canvas/editor/')) {
    const parts = window.location.pathname.split('/').filter(Boolean);
    // The parameter is `/canvas/editor/{entity_type}/{entity_id}
    entityType = parts[2] ?? '';
    const tmpEntityId = parts[3] ?? '';
    entityId = tmpEntityId.length ? parseInt(tmpEntityId) : 0;
  } else {
    entityId = window?.drupalSettings?.canvas?.entityId
      ? parseInt(window.drupalSettings.canvas.entityId)
      : 0;
    entityType = window?.drupalSettings?.canvas?.entityType ?? '';
  }

  if (!accountId) {
    return 'No conductor account ID found.';
  }

  if (
    !Number.isInteger(maxDrafts) ||
    !Number.isInteger(usedDrafts) ||
    (maxDrafts === 0 && usedDrafts === 0)
  ) {
    return 'Draft usage information is not available. Please reload the app.';
  }

  if (!entityType || !entityId) {
    return 'Please open a Canvas page before using this extension.';
  }

  return (
    <ErrorBoundary onReset={() => setAppKey((k) => k + 1)}>
      <AppStateProvider
        key={appKey}
        initialState={{
          accountId,
          draft: { id: draftId },
          drupal: { entity: { type: entityType, id: entityId }, draftLinked: draftId.length > 0 },
          draftUsage: { maxDrafts, usedDrafts, alertIsDismissed: false },
        }}
      >
        <AppInner />
      </AppStateProvider>
    </ErrorBoundary>
  );
}

export default App;
