import React, { forwardRef, useEffect, useState } from 'react';
import { useNavigate } from "react-router-dom";
import useMediaQuery from '@mui/material/useMediaQuery';
import Box from '@mui/material/Box';
import { useTheme } from '@mui/material/styles';
import MuiMarkdown from 'mui-markdown';

import { BackstoryPageProps } from '../components/BackstoryTab';
import { Conversation, ConversationHandle } from '../components/Conversation';
import { ChatQuery } from '../components/ChatQuery';
import { MessageList } from '../components/Message';
import { CandidateInfo } from 'components/CandidateInfo';
import { connectionBase } from '../Global';
import { LoadingComponent } from 'components/LoadingComponent';
import { useUser } from "../components/UserContext";
import { Candidate, Tunables } from "../types/types";
import { Navigate } from 'react-router-dom';

const ChatPage = forwardRef<ConversationHandle, BackstoryPageProps>((props: BackstoryPageProps, ref) => {
    const navigate = useNavigate();
    const { sessionId, setSnack, submitQuery } = props;
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    const [questions, setQuestions] = useState<React.ReactElement[]>([]);
    const { user } = useUser();
  const candidate: Candidate | null = (user && user.userType === "UserType.CANDIDATE") ? user as Candidate : null;

  useEffect(() => {
    if (!candidate) {
      return;
    }

    setQuestions([
      <Box sx={{ display: "flex", flexDirection: isMobile ? "column" : "row" }}>
        {candidate.questions?.map(({ question, tunables }, i: number) =>
          <ChatQuery key={i} query={{ prompt: question, tunables: tunables }} submitQuery={submitQuery} />
        )}
    </Box>,
    <Box sx={{ p: 1 }}>
      <MuiMarkdown>
        {`As with all LLM interactions, the results may not be 100% accurate. Please contact **${candidate.fullName}** if you have any questions.`}
      </MuiMarkdown>
      </Box>]);
  }, [candidate, isMobile, submitQuery]);

  if (!candidate) {
        return (<></>);
    }
    return (
        <Box>
            <CandidateInfo sessionId={sessionId} action="Chat with Backstory AI about " />
            <Conversation
                ref={ref}
                {...{
                    multiline: true,
                    type: "chat",
            placeholder: `What would you like to know about ${candidate?.firstName}?`,
                    resetLabel: "chat",
                    sessionId,
                    setSnack,
                    defaultPrompts: questions,
                    submitQuery,
                }} />
        </Box>);
});

export {
  ChatPage
};