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/ui/CandidateInfo';
import { useAuth } from 'hooks/AuthContext';
import { Candidate } from 'types/types';
import { useAppState } from 'hooks/GlobalContext';

const ChatPage = forwardRef<ConversationHandle, BackstoryPageProps>((props: BackstoryPageProps, ref) => {
  const { setSnack } = useAppState();
  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((q, i: number) =>
          <BackstoryQuery key={i} question={q} />
        )}
    </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]);

  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",
            defaultPrompts: questions,
                }} />
        </Box>);
});

export {
  ChatPage
};