"use client";

import React, { useEffect, useState } from "react";
import {
  Card,
  Typography,
  Grid,
  Button,
  TextField as MaterialTextField,
  IconButton,
} from "@mui/material";
import {
  Show,
  SimpleShowLayout,
  TextField,
  ShowProps,
  useGetOne,
  useRefresh,
  BooleanField,
} from "react-admin";
import QRCode from "react-qr-code";
import useSWR from "swr";
import RefreshIcon from "@mui/icons-material/Refresh";

const Sidebar = ({ record }: any) => {
  const [receivedMessages, setReceivedMessages] = useState([]);
  const [phoneNumber, setPhoneNumber] = useState("");
  const handlePhoneNumberChange = (event: any) => {
    setPhoneNumber(event.target.value);
  };

  const [message, setMessage] = useState("");
  const handleMessageChange = (event: any) => {
    setMessage(event.target.value);
  };

  const sendMessage = async (phoneNumber: string, message: string) => {
    await fetch(`/api/v1/whatsapp/bots/${record.token}/send`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ phoneNumber, message }),
    });
  };

  const receiveMessages = async () => {
    const result = await fetch(`/api/v1/whatsapp/bots/${record.token}/receive`);
    const msgs = await result.json();
    console.log(msgs);
    setReceivedMessages(msgs);
  };

  return (
    <Card style={{ width: "33%", marginLeft: 20, padding: 14 }}>
      <Grid container direction="column" spacing={2}>
        <Grid item>
          <Typography variant="h6">Send message</Typography>
        </Grid>
        <Grid item>
          <MaterialTextField
            variant="outlined"
            label="Phone number"
            fullWidth
            size="small"
            value={phoneNumber}
            onChange={handlePhoneNumberChange}
          />
        </Grid>
        <Grid item>
          <MaterialTextField
            variant="outlined"
            label="Message"
            multiline
            rows={3}
            fullWidth
            size="small"
            value={message}
            onChange={handleMessageChange}
          />
        </Grid>
        <Grid item container direction="row-reverse">
          <Button
            variant="contained"
            color="primary"
            onClick={() => sendMessage(phoneNumber, message)}
          >
            Send
          </Button>
        </Grid>
        <Grid item container direction="row">
          <Grid item>
            <Typography variant="h6">Receive messages</Typography>
          </Grid>
          <Grid item>
            <IconButton
              onClick={receiveMessages}
              color="primary"
              style={{ marginTop: -12 }}
            >
              <RefreshIcon />
            </IconButton>
          </Grid>
        </Grid>
        {receivedMessages.map((receivedMessage: any, index: number) => (
          <Grid key={index} item container direction="column" spacing={1}>
            <Grid item style={{ fontWeight: "bold", color: "#999" }}>
              {receivedMessage.key.remoteJid.replace("@s.whatsapp.net", "")}
            </Grid>
            <Grid item style={{ borderBottom: "1px solid #999" }}>
              {receivedMessage.message.conversation}
            </Grid>
          </Grid>
        ))}
      </Grid>
    </Card>
  );
};

const WhatsappBotShow = (props: ShowProps) => {
  const refresh = useRefresh();
  const { data } = useGetOne("whatsappBots", {id: props.id});

  const { data: registerData, error: registerError } = useSWR(
    data && !data?.isVerified
      ? `/api/v1/whatsapp/bots/${props.id}/register`
      : undefined,
    { refreshInterval: 59000 }
  );

  const unverifyBot = async () => {
    await fetch(`/api/v1/whatsapp/bots/${props.id}/unverify`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ verified: false }),
    });
  };

  console.log({ registerData, registerError });

  useEffect(() => {
    if (data && !data?.isVerified) {
      const interval = setInterval(() => {
        refresh();
      }, 10000);
      return () => clearInterval(interval);
    }

    return undefined;
  }, [refresh, data]);

  return (
    <Show {...props} title="Bot" aside={<Sidebar />}>
      <SimpleShowLayout>
        <TextField source="phoneNumber" />
        <BooleanField source="isVerified" />
        <Button
          color="primary"
          size="small"
          style={{ color: "black", backgroundColor: "#ddd" }}
          onClick={async () => unverifyBot()}
        >
          Unverify
        </Button>
        <TextField source="description" />
        <TextField source="token" />
        {!data?.isVerified && data?.qrCode && data?.qrCode !== "" && (
          <QRCode value={data.qrCode} />
        )}
      </SimpleShowLayout>
    </Show>
  );
};

export default WhatsappBotShow;
