/**
 * @file FieldsNotesTrackingPanel.tsx - Middle panel of the Processing page that provides a tabbed interface for viewing and editing work item metadata.
 *
 * Contains three tabs:
 * - Fields: folder fields (when folder node selected) or document template fields (when document selected)
 * - Notes: work item or document-level notes with add capability
 * - Tracking: chronological tracking records (visible based on permission or assignment)
 *
 * Displays the currently selected node's name and icon above the tab content.
 * The default active tab is "notes" if folder-level notes exist, otherwise "fields".
 */

import { type FC, useState } from 'react';
import { ContentCard } from '../../ContentCard.tsx';
import { Tab, Tabs } from 'react-bootstrap';
import {
  type DocumentNode,
  type FolderNode,
  getDocumentIcon,
} from '../DetailsFolderPanel/sections/FolderSection/FolderTree.tsx';
import { Icon } from '../../Icon.tsx';
import { useProcessPermissions } from '../../../contexts/ProcessPermissionsContext.tsx';
import { AtAllowRights } from '../../../types/atAllowRights.ts';
import { useWorkItem } from '../../../contexts/WorkItemContext.tsx';
import { useProcessingUI } from '../../../contexts/ProcessingUIContext.tsx';
import { TrackingTab } from './tabs/TrackingTab.tsx';
import { NotesTab } from './tabs/NotesTab.tsx';
import { FieldsTab } from './tabs/FieldsTab.tsx';
import { useAuth } from '../../../contexts/AuthContext.tsx';
import { useTranslation } from 'react-i18next';

/**
 * Tabbed container for displaying/editing WorkItem metadata, including folder/document fields, notes, and tracking records.
 * The Tracking tab is only visible if the user has ViewTracking permission or is the assigned user.
 */
export const FieldsNotesTrackingPanel: FC = () => {
  // Required contexts for work item processing
  const { workItem, documents, notes, trackingRecords } = useWorkItem();
  const { selectedNode } = useProcessingUI();
  const { hasPermission } = useProcessPermissions();
  const { username } = useAuth();

  // Default to "notes" tab if folder-level notes exist, otherwise start on "fields"
  const [activeTabKey, setActiveTabKey] = useState(
    notes.filter((note) => !note.documentId).length ? 'notes' : 'fields'
  );

  const { t } = useTranslation(undefined, {
    keyPrefix: 'components.processing.fields_notes_tracking_panel',
  });

  return (
    <ContentCard
      headerContent={{
        children: (
          <div className={'card-header pb-0'}>
            <Tabs
              justify
              activeKey={activeTabKey}
              onSelect={(key) => setActiveTabKey(key as string)}
              className={'border-bottom-0'}
            >
              <Tab eventKey={'fields'} title={t('card.header.tabs.fields')} />
              <Tab eventKey={'notes'} title={t('card.header.tabs.notes')} />
              {(hasPermission(AtAllowRights.ViewTracking) ||
                workItem?.assignedTo?.toLowerCase() ===
                  username?.toLowerCase()) && (
                <Tab
                  eventKey={'tracking'}
                  title={t('card.header.tabs.tracking')}
                />
              )}
            </Tabs>
          </div>
        ),
      }}
      fillPage
    >
      {/* Show folder/document name and icon */}
      {((selectedNode as FolderNode)?.folderId !== undefined ||
        activeTabKey === 'tracking') && (
        <>
          <div className={'d-flex gap-2 align-items-center'}>
            <span className={'d-flex align-items-center'}>
              <Icon
                iconName={'Folder2Open'}
                size={32}
                className={'text-warning'}
              />
            </span>
            <span className={'fs-4 text-break'}>{workItem?.description}</span>
          </div>
          <hr />
        </>
      )}
      {(selectedNode as DocumentNode)?.documentId !== undefined &&
        activeTabKey !== 'tracking' &&
        (() => {
          const document = documents.find(
            (_document) =>
              _document.documentId === (selectedNode as DocumentNode).documentId
          );
          const icon = getDocumentIcon(document as DocumentNode);

          return (
            <>
              <div className={'d-flex gap-2 align-items-center'}>
                <span className={'d-flex align-items-center'}>
                  <Icon
                    iconName={icon.iconName}
                    size={32}
                    className={icon.colorClass}
                  />
                </span>
                <span className={'fs-4 text-break'}>
                  {document?.documentName}
                </span>
              </div>
              <hr />
            </>
          );
        })()}

      {/* Fields tab */}
      {<FieldsTab show={activeTabKey === 'fields'} />}

      {/* Notes tab */}
      {<NotesTab show={activeTabKey === 'notes'} />}

      {/* Tracking tab */}
      {
        <TrackingTab
          show={activeTabKey === 'tracking' && Boolean(trackingRecords)}
        />
      }
    </ContentCard>
  );
};
