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

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

export interface UdbContext {
  instanceId: string;
  mandateId?: string;
  featureInstanceId?: string;
  userId?: 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) => void;
  className?: string;
}

const _TAB_LABELS: Record<UdbTab, Record<string, string>> = {
  chats: { de: 'Chats', en: 'Chats', fr: 'Chats' },
  files: { de: 'Dateien', en: 'Files', fr: 'Fichiers' },
  sources: { de: 'Quellen', en: 'Sources', fr: 'Sources' },
};

const UnifiedDataBar: React.FC<UnifiedDataBarProps> = ({
  context,
  activeTab: controlledTab,
  onTabChange,
  hideTabs,
  onSelectChat,
  activeWorkflowId,
  onCreateNewChat,
  onRenameChat,
  onDeleteChat,
  onChatDragStart,
  onFileSelect,
  className,
}) => {
  const visibleTabs = (['chats', 'files', 'sources'] as UdbTab[]).filter(
    t => !hideTabs?.includes(t),
  );
  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)}
          >
            {_TAB_LABELS[tab].de}
          </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}
          />
        )}
        {currentTab === 'sources' && !hideTabs?.includes('sources') && (
          <SourcesTab context={context} />
        )}
      </div>
    </div>
  );
};

export default UnifiedDataBar;
