import { FC, useState } from "react";
import { Grid, Button, Dialog, DialogActions, DialogContent, TextField } from "@mui/material";
// import { request, gql } from "graphql-request";

interface ArticleCreateDialogProps {
  ticketID: string;
  open: boolean;
  closeDialog: () => void;
  kind: "reply" | "note";
}

export const ArticleCreateDialog: FC<ArticleCreateDialogProps> = ({ ticketID, open, closeDialog, kind }) => {
  console.log({ ticketID })
  const [body, setBody] = useState("");
  const backgroundColor = kind === "reply" ? "#1982FC" : "#FFB620";
  const color = kind === "reply" ? "white" : "black";
  const origin = typeof window !== 'undefined' && window.location.origin
    ? window.location.origin
    : '';
  const createArticle = async () => {
    // const token = document?.querySelector('meta[name="csrf-token"]').getAttribute('content');
    // console.log({ token })
    const res = await fetch(`${origin}/api/v1/ticket_articles`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-CSRF-Token": "BG3wYuvTgi4ALfaZ-Mdq6i08wRFRJHeCPJbfGjfVarLRhwaxRC8J-AZvGiSNOiWrN38WT3C9WGLhcmaMb0AqBQ",
      },
      body: JSON.stringify({
        ticket_id: ticketID,
        body,
        internal: kind === "note",
        sender: "Agent",
      }),
    });
    console.log({ res })
    /*
    const document = gql`

  mutation {
        ticketUpdate(
          input: {
            ticketId: "1"
            body: "This is a test article"
            internal: false
          }
        ) {
          article {
            id
          }
        }
      }
    `;
    const data = await request({
      url: `${origin}/graphql`,
      document,
    });

    console.log({ data })
    */
    closeDialog();
    setBody("");
  }

  return (
    <Dialog open={open} maxWidth="sm" fullWidth >
      <DialogContent>
        <TextField label={kind === "reply" ? "Write reply" : "Write internal note"} multiline rows={10} fullWidth value={body} onChange={(e: any) => setBody(e.target.value)} />
      </DialogContent>
      <DialogActions sx={{ px: 3, pt: 0, pb: 3 }}>
        <Grid container justifyContent="space-between">
          <Grid item>
            <Button sx={{
              backgroundColor: "white", color: "#666", fontFamily: "Poppins, sans-serif",
              fontWeight: 700,
              borderRadius: 2,
              textTransform: "none",
            }}
              onClick={() => { setBody(""); closeDialog() }}>Cancel</Button>
          </Grid>
          <Grid item>
            <Button sx={{
              backgroundColor, color, fontFamily: "Poppins, sans-serif",
              fontWeight: 700,
              borderRadius: 2,
              textTransform: "none",
              px: 3
            }}
              onClick={createArticle}
            >{kind === "reply" ? "Send Reply" : "Save Note"}</Button>
          </Grid>
        </Grid>
      </DialogActions>
    </Dialog >

  );
};
