import React from "react";
import Markdown from "markdown-to-jsx";
import styled, { keyframes } from "styled-components";

const fadeIn = keyframes`
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
`;

const MessageContainer = styled.div<{ $isUser: boolean }>`
  display: flex;
  justify-content: ${(props) => (props.$isUser ? "flex-end" : "flex-start")};
  margin-bottom: 1.5rem;
  width: 100%;
  animation: ${fadeIn} 0.3s ease-out;
`;

const Bubble = styled.div<{ $isUser: boolean }>`
  max-width: 80%;
  padding: 1rem 1.5rem;
  border-radius: 1.2rem;
  background: ${(props) =>
    props.$isUser
      ? `linear-gradient(135deg, ${props.theme.main} 0%, ${props.theme.focus} 100%)`
      : props.theme.darkMode
        ? "rgba(255, 255, 255, 0.1)"
        : "rgba(0, 0, 0, 0.7)"}; // Dark background for AI in light mode as requested
  color: #fff; // Text stays white as background is always dark/colored
  backdrop-filter: blur(10px);
  border: 1px solid ${(props) => props.theme.darkMode ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.1)"};
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  font-size: 1rem;
  line-height: 1.6;
  border-bottom-right-radius: ${(props) => (props.$isUser ? "0.2rem" : "1.2rem")};
  border-bottom-left-radius: ${(props) => (props.$isUser ? "1.2rem" : "0.2rem")};

  & pre {
    background: rgba(0, 0, 0, 0.3);
    padding: 1rem;
    border-radius: 0.5rem;
    overflow-x: auto;
  }

  & code {
    font-family: 'Fira Code', monospace;
    font-size: 0.9em;
  }
  
  & a {
    color: #a0c4ff;
    text-decoration: underline;
  }
`;

const LoadingDot = styled.div`
  width: 8px;
  height: 8px;
  background: #fff;
  border-radius: 50%;
  margin: 0 4px;
  animation: bounce 1.4s infinite ease-in-out both;

  &:nth-child(1) { animation-delay: -0.32s; }
  &:nth-child(2) { animation-delay: -0.16s; }
  
  @keyframes bounce {
    0%, 80%, 100% { transform: scale(0); }
    40% { transform: scale(1); }
  }
`;

const LoadingContainer = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0.5rem;
`;

type ConversationDetailCardProps = {
  message: string;
  user_created: boolean;
};

// Custom component for rendering plots
const MyPlot = ({ format, image }: { format: string; image: string }) => {
  const imageSrc = `data:image/${format};base64,${image}`;
  return (
    <img
      src={imageSrc}
      style={{ maxWidth: "100%", height: "auto", borderRadius: "8px", marginTop: "10px" }}
      alt="plot"
    />
  );
};

// Custom component for rendering errors
const MyError = ({ content }: { content: string }) => {
  return (
    <span style={{ color: "#ff6b6b", fontWeight: "bold", display: "block", marginTop: "0.5rem" }}>
      Error: {content}
    </span>
  );
};

const ConversationDetailCard = ({
  message,
  user_created,
}: ConversationDetailCardProps): JSX.Element => {
  if (message.length === 0) {
    return (
      <MessageContainer $isUser={false}>
        <Bubble $isUser={false}>
          <LoadingContainer>
            <LoadingDot />
            <LoadingDot />
            <LoadingDot />
          </LoadingContainer>
        </Bubble>
      </MessageContainer>
    );
  }

  let contentToAdd = message;
  try {
    const parsedMessage = JSON.parse(message);
    if (
      parsedMessage &&
      typeof parsedMessage === "object" &&
      parsedMessage.type
    ) {
      switch (parsedMessage.type) {
        case "text":
          contentToAdd = parsedMessage.content;
          break;
        case "plot":
          contentToAdd = `<plot format="${parsedMessage.format}" image="${parsedMessage.image}"></plot>`;
          break;
        case "error":
          contentToAdd = `<error content="${parsedMessage.content}"></error>`;
          break;
        default:
          break;
      }
    }
  } catch { }

  return (
    <MessageContainer $isUser={user_created}>
      <Bubble $isUser={user_created}>
        <Markdown
          className="display-linebreak"
          style={{ whiteSpace: "pre-line" }}
          options={{
            overrides: {
              plot: {
                component: MyPlot,
              },
              error: {
                component: MyError,
              },
            },
          }}
        >
          {contentToAdd}
        </Markdown>
      </Bubble>
    </MessageContainer>
  );
};

export default ConversationDetailCard;
