import React, { useState } from 'react';
import ChatsTab from './ChatsTab';
import FilesTab from './FilesTab';
import SourcesTab from './SourcesTab';
import { useLanguage } from '../../providers/language/LanguageContext';
import styles from './UnifiedDataBar.module.css';

export type UdbTab = 'chats' | 'files' | 'sources';

/** Aufruf-Surface, in der die UDB gerade lebt. Wird an `FolderTree.udbContext`
 * weitergereicht, damit Custom-Actions (z. B. `workflow.openInEditor`) sich
 * pro Surface registrieren können. */
export type UdbSurface =
  | 'workspace'
  | 'graphEditor'
  | 'trustee'
  | 'standalone'
  | 'sharepoint';

export interface UdbContext {
  instanceId: string;
  mandateId?: string;
  featureInstanceId?: string;
  userId?: string;
  /** Optionales Surface-Tag, hilft Custom-Actions zu entscheiden, wann sie sichtbar sind. */
  surface?: UdbSurface;
}

export interface AddToChat_FileItem {
  id: string;
  type: 'file' | 'folder';
  name: string;
}

export interface AddToChat_FeatureSource {
  featureInstanceId: string;
  featureCode: string;
  tableName?: string;
  objectKey: string;
  label: string;
}

interface UnifiedDataBarProps {
  context: UdbContext;
  activeTab?: UdbTab;
  onTabChange?: (tab: UdbTab) => void;
  hideTabs?: UdbTab[];
  onSelectChat?: (chatId: string, featureInstanceId: string) => void;
  activeWorkflowId?: string;
  onCreateNewChat?: () => void;
  onRenameChat?: (chatId: string, newName: string) => void;
  onDeleteChat?: (chatId: string) => void;
  onChatDragStart?: (chatId: string, event: React.DragEvent) => void;
  onFileSelect?: (fileId: string, fileName?: string) => void;
  onSourcesChanged?: () => void;
  onSendToChat_Files?: (items: AddToChat_FileItem[]) => void;
  onSendToChat_FeatureSource?: (params: AddToChat_FeatureSource) => void;
  onAttachDataSource?: (dsId: string) => void;
  /** Wird aufgerufen, sobald aus der UDB-FilesTab ein Workflow-File in den
   * Graph-Editor importiert wurde (Action `workflow.openInEditor`). */
  onWorkflowImportedFromFile?: (workflowId: string) => void;
  className?: string;
}

function _tabLabel(tab: UdbTab, t: (k: string) => string): string {
  switch (tab) {
    case 'chats': return t('Chatverläufe');
    case 'files': return t('Dateien');
    case 'sources': return t('Quellen');
    default: return tab;
  }
}

const UnifiedDataBar: React.FC<UnifiedDataBarProps> = ({
  context,
  activeTab: controlledTab,
  onTabChange,
  hideTabs,
  onSelectChat,
  activeWorkflowId,
  onCreateNewChat,
  onRenameChat,
  onDeleteChat,
  onChatDragStart,
  onFileSelect,
  onSourcesChanged,
  onSendToChat_Files,
  onSendToChat_FeatureSource,
  onAttachDataSource,
  onWorkflowImportedFromFile,
  className,
}) => {
  const { t } = useLanguage();
  const visibleTabs = (['chats', 'files', 'sources'] as UdbTab[]).filter(
    (ubTab) => !hideTabs?.includes(ubTab),
  );
  const [internalTab, setInternalTab] = useState<UdbTab>(controlledTab ?? visibleTabs[0] ?? 'chats');
  const currentTab = controlledTab ?? internalTab;

  const _handleTabChange = (tab: UdbTab) => {
    setInternalTab(tab);
    onTabChange?.(tab);
  };

  return (
    <div className={`${styles.udb} ${className || ''}`}>
      <div className={styles.tabBar}>
        {visibleTabs.map((tab) => (
          <button
            key={tab}
            className={`${styles.tab} ${currentTab === tab ? styles.tabActive : ''}`}
            onClick={() => _handleTabChange(tab)}
          >
            {_tabLabel(tab, t)}
          </button>
        ))}
      </div>
      <div className={styles.tabContent}>
        {currentTab === 'chats' && !hideTabs?.includes('chats') && (
          <ChatsTab
            context={context}
            onSelectChat={onSelectChat}
            onDragStart={onChatDragStart}
            activeWorkflowId={activeWorkflowId}
            onCreateNew={onCreateNewChat}
            onRenameChat={onRenameChat}
            onDeleteChat={onDeleteChat}
          />
        )}
        {currentTab === 'files' && !hideTabs?.includes('files') && (
          <FilesTab
            context={context}
            onFileSelect={onFileSelect}
            onSendToChat={onSendToChat_Files}
            onWorkflowImported={onWorkflowImportedFromFile}
          />
        )}
        {currentTab === 'sources' && !hideTabs?.includes('sources') && (
          <SourcesTab
            context={context}
            onSourcesChanged={onSourcesChanged}
            onSendToChat_FeatureSource={onSendToChat_FeatureSource}
            onAttachDataSource={onAttachDataSource}
          />
        )}
      </div>
    </div>
  );
};

export default UnifiedDataBar;
