import React, { forwardRef, useEffect, useState } from 'react';
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 { BackstoryQuery } from '../components/BackstoryQuery';
import { CandidateInfo } from 'components/CandidateInfo';
import { useAuth } from 'hooks/AuthContext';
import { Candidate } from 'types/types';

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

  //  console.log("ChatPage candidate =>", candidate);
  useEffect(() => {
    if (!candidate) {
      return;
    }

    setQuestions([
      <Box sx={{ display: "flex", flexDirection: isMobile ? "column" : "row" }}>
        {candidate.questions?.map(({ question, tunables }, i: number) =>
          <BackstoryQuery 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 candidate={candidate} 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",
                    setSnack,
                    defaultPrompts: questions,
                    submitQuery,
                }} />
        </Box>);
});

export {
  ChatPage
};