import { useState } from 'react';
import { useParams } from 'react-router';
import { useQueryClient } from '@tanstack/react-query';
import type { SessionEntry } from 'widgets/Chat';
import { useClaude } from './useClaude';
import { useOpenCode } from './useOpenCode';
import { ChatPanel } from './ChatPanel';
import { useVisibleClaudeModels, useVisibleOpenCodeModels } from '@/state/useModels';

export const ClaudeChat = () => {
  const { sessionId } = useParams<{ sessionId: string }>();
  const queryClient = useQueryClient();
  const sessions = queryClient.getQueryData<SessionEntry[]>(['SESSIONS']);
  const sessionModel = sessions?.find((s) => s.id === sessionId)?.model;
  const claude = useClaude(sessionId, sessionModel);
  const claudeModels = useVisibleClaudeModels();

  return (
    <div className="flex items-center justify-center h-full md:p-4">
      <div className="flex flex-col w-full h-full md:w-3/4 md:h-3/4 lg:w-1/2 lg:h-1/2">
        <ChatPanel chat={claude} provider="claude" availableModels={claudeModels} />
      </div>
    </div>
  );
};

export const OpenCodeChat = () => {
  const { sessionId } = useParams<{ sessionId: string }>();
  const queryClient = useQueryClient();
  const sessions = queryClient.getQueryData<SessionEntry[]>(['OC_SESSIONS']);
  const sessionModel = sessions?.find((s) => s.id === sessionId)?.model;
  const opencode = useOpenCode(sessionId, sessionModel);
  const openCodeModels = useVisibleOpenCodeModels();

  return (
    <div className="flex items-center justify-center h-full md:p-4">
      <div className="flex flex-col w-full h-full md:w-3/4 md:h-3/4 lg:w-1/2 lg:h-1/2">
        <ChatPanel chat={opencode} provider="opencode" availableModels={openCodeModels} />
      </div>
    </div>
  );
};

const ClaudeNewChatInner = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode') => void }) => {
  const claude = useClaude();
  const claudeModels = useVisibleClaudeModels();
  return (
    <ChatPanel chat={claude} provider="claude" availableModels={claudeModels} onProviderChange={onProviderChange} />
  );
};

const OpenCodeNewChatInner = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode') => void }) => {
  const opencode = useOpenCode();
  const openCodeModels = useVisibleOpenCodeModels();
  return (
    <ChatPanel
      chat={opencode}
      provider="opencode"
      availableModels={openCodeModels}
      onProviderChange={onProviderChange}
    />
  );
};

export const NewChat = () => {
  const [provider, setProvider] = useState<'claude' | 'opencode'>('claude');

  return (
    <div className="flex items-center justify-center h-full md:p-4">
      <div className="flex flex-col w-full h-full md:w-3/4 md:h-3/4 lg:w-1/2 lg:h-1/2">
        {provider === 'claude' ? (
          <ClaudeNewChatInner key="claude" onProviderChange={setProvider} />
        ) : (
          <OpenCodeNewChatInner key="opencode" onProviderChange={setProvider} />
        )}
      </div>
    </div>
  );
};
