import SendIcon from "@mui/icons-material/Send";
import { Button, TextField, useTheme } from "@mui/material";
import Grid from "@mui/material/Unstable_Grid2";
import { useState } from "react";
import { useSnackbar } from "notistack";
import postData from "../../services/api/basePostData";

export default function SendMessage({ fetchMessages }) {
  const [userMessage, setUserMessage] = useState("");
  const { enqueueSnackbar } = useSnackbar();
  const theme = useTheme();

  const onMessageChange = (e) => {
    setUserMessage(e.target.value);
  };

  const onPressButton = () => {
    const url = `/query/query_search`;

    if (!userMessage.trim()) {
      enqueueSnackbar("Please enter a message.", {
        variant: "warning",
      });
      return;
    }

    const data = { q: userMessage };

    postData(url, data)
      .then(fetchMessages)
      .catch((error) => {
        enqueueSnackbar(error.detail || error.message, {
          variant: "error",
        });
      });

    setUserMessage("");
  };

  return (
    <>
      <Grid
        container
        alignItems={"center"}
        xs={12}
        sm={12}
        p={2}
        pl={3}
        border={1}
        borderRadius={2}
        borderColor={theme.palette.border.default}
        sx={{
          backgroundColor: theme.palette.background.default,
        }}
      >
        <Grid item xs={12} sm={10}>
          <TextField
            fullWidth
            size="small"
            label="Ask me anything"
            onChange={onMessageChange}
            slotProps={{
              input: {
                sx: {
                  backgroundColor: "white",
                  borderRadius: "4px",
                },
              },
            }}
          />
        </Grid>

        <Grid
          ml={4}
          item
          xs={12}
          border={1}
          borderColor={theme.palette.border.default}
          borderRadius={20}
          display="flex"
          justifyContent="center"
          alignItems="center"
          sx={{
            backgroundColor: theme.palette.secondary.main,
            width: 35,
            height: 35,
          }}
        >
          <Button onClick={onPressButton}>
            <SendIcon
              fontSize="small"
              sx={{
                color: theme.palette.border.default,
              }}
            />
          </Button>
        </Grid>
      </Grid>
    </>
  );
}
