'use client';

import React from 'react';
import { CollapseFileButton } from './CollapseFileButton';
import { useChatLayoutContextSelector } from '../../ChatLayoutContext';
import { FileContainerHeaderVersionHistory } from './FileContainerHeaderVersionHistory';
import { SelectedFileButtonsRecord, SelectedFileSegmentRecord } from './config';
import { FileType } from '@/api/asset_interfaces/chat';

export const FileContainerHeader: React.FC = React.memo(() => {
  const selectedFileType = useChatLayoutContextSelector((x) => x.selectedFile?.type);
  const selectedFileId = useChatLayoutContextSelector((x) => x.selectedFile?.id);
  const isVersionHistoryMode = useChatLayoutContextSelector((x) => x.isVersionHistoryMode);

  if (isVersionHistoryMode) return <FileContainerHeaderVersionHistory />;

  return (
    <FileContainerHeaderStandard
      selectedFileId={selectedFileId}
      selectedFileType={selectedFileType}
    />
  );
});

FileContainerHeader.displayName = 'FileContainerHeader';

const FileContainerHeaderStandard: React.FC<{
  selectedFileId: string | undefined;
  selectedFileType: FileType | undefined;
}> = ({ selectedFileId, selectedFileType }) => {
  const chatId = useChatLayoutContextSelector((x) => x.chatId);
  const selectedFileView = useChatLayoutContextSelector((x) => x.selectedFileView);
  const onCollapseFileClick = useChatLayoutContextSelector((state) => state.onCollapseFileClick);
  const selectedLayout = useChatLayoutContextSelector((x) => x.selectedLayout);
  const showCollapseButton = selectedLayout === 'both';

  const SelectedFileSegment = React.useMemo(
    () =>
      selectedFileType && SelectedFileSegmentRecord[selectedFileType]
        ? SelectedFileSegmentRecord[selectedFileType]
        : () => <></>,
    [selectedFileType]
  );

  const SelectedFileButtons = React.useMemo(
    () =>
      selectedFileType && SelectedFileButtonsRecord[selectedFileType]
        ? SelectedFileButtonsRecord[selectedFileType]
        : () => null,
    [selectedFileType]
  );

  return (
    <>
      <div className="flex min-w-0 shrink items-center gap-1.5 overflow-hidden">
        <CollapseFileButton
          showCollapseButton={showCollapseButton}
          onCollapseFileClick={onCollapseFileClick}
        />
        {selectedFileView && (
          <SelectedFileSegment
            selectedFileView={selectedFileView}
            selectedFileId={selectedFileId}
            chatId={chatId}
          />
        )}
      </div>
      <div className="flex-1">
        <SelectedFileButtons selectedFileView={selectedFileView} selectedFileId={selectedFileId} />
      </div>
    </>
  );
};
