'use client';

import React from 'react';

import type { ChatMessage, ProcessArtifact, ProcessEvent, ProcessRun } from '@/types';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { MessageList } from '@/components/chat-workbench/MessageList';
import { ArtifactSidebar } from '@/components/chat-workbench/ArtifactSidebar';
import { pickAppText } from '@/lib/i18n/core';
import { useAppI18n } from '@/lib/i18n/provider';

export function ChatWorkbench({
  messages,
  isThinking,
  messagesEndRef,
  messageViewportRef,
  processRuns,
  processEvents,
  processArtifacts,
  selectedRunId,
  onSelectRun,
  onCancelRun,
}: {
  messages: ChatMessage[];
  isThinking: boolean;
  messagesEndRef: React.RefObject<HTMLDivElement>;
  messageViewportRef: React.RefObject<HTMLDivElement>;
  processRuns: ProcessRun[];
  processEvents: ProcessEvent[];
  processArtifacts: ProcessArtifact[];
  selectedRunId: string | null;
  onSelectRun: (runId: string) => void;
  onCancelRun: (runId: string) => void;
}) {
  const { locale } = useAppI18n();
  const [isDesktop, setIsDesktop] = React.useState(() =>
    typeof window === 'undefined' ? true : window.matchMedia('(min-width: 1024px)').matches
  );

  React.useEffect(() => {
    if (typeof window === 'undefined') {
      return;
    }

    const mediaQuery = window.matchMedia('(min-width: 1024px)');
    const updateLayout = () => setIsDesktop(mediaQuery.matches);
    updateLayout();

    if (typeof mediaQuery.addEventListener === 'function') {
      mediaQuery.addEventListener('change', updateLayout);
      return () => mediaQuery.removeEventListener('change', updateLayout);
    }

    mediaQuery.addListener(updateLayout);
    return () => mediaQuery.removeListener(updateLayout);
  }, []);

  const selectedRun = selectedRunId
    ? processRuns.find((item) => item.run_id === selectedRunId) || null
    : null;
  const selectedRunEvents = selectedRun
    ? processEvents.filter((item) => item.run_id === selectedRun.run_id)
    : [];
  const selectedRunArtifacts = selectedRun
    ? processArtifacts.filter((item) => item.run_id === selectedRun.run_id)
    : [];
  const hasResultsPanel = Boolean(
    selectedRun &&
      (
        selectedRun.summary ||
        selectedRunEvents.length > 0 ||
        selectedRunArtifacts.length > 0
      )
  );
  const desktopColumns = hasResultsPanel
    ? 'grid-cols-[minmax(0,1fr)_360px]'
    : 'grid-cols-[minmax(0,1fr)]';

  const messageList = (
    <MessageList
      messages={messages}
      isThinking={isThinking}
      messagesEndRef={messagesEndRef}
      viewportRef={messageViewportRef}
      processRuns={processRuns}
      processEvents={processEvents}
      processArtifacts={processArtifacts}
      selectedRunId={selectedRun?.run_id || null}
      onSelectRun={onSelectRun}
      onCancelRun={onCancelRun}
    />
  );

  if (isDesktop) {
    return (
      <div className={`grid h-full ${desktopColumns}`}>
        <div className="min-h-0">
          {messageList}
        </div>
        {hasResultsPanel && (
          <div className="min-h-0">
            <ArtifactSidebar
              selectedRun={selectedRun}
              events={processEvents}
              artifacts={processArtifacts}
            />
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="h-full">
      {!hasResultsPanel ? (
        messageList
      ) : (
        <Tabs defaultValue="chat" className="h-full flex flex-col">
          <div className="px-4 pt-3 border-b border-border">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="chat">{pickAppText(locale, '聊天', 'Chat')}</TabsTrigger>
              <TabsTrigger value="results">{pickAppText(locale, '结果', 'Results')}</TabsTrigger>
            </TabsList>
          </div>
          <TabsContent value="chat" className="flex-1 min-h-0 mt-0">
            {messageList}
          </TabsContent>
          <TabsContent value="results" className="flex-1 min-h-0 mt-0">
            <ArtifactSidebar
              selectedRun={selectedRun}
              events={processEvents}
              artifacts={processArtifacts}
            />
          </TabsContent>
        </Tabs>
      )}
    </div>
  );
}
