"use client";

import { FC, useState } from "react";
import {
  Grid,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  TextField,
} from "@mui/material";
import { useSWRConfig } from "swr";
import { updateTicketMutation } from "app/_graphql/updateTicketMutation";

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

export const ArticleCreateDialog: FC<ArticleCreateDialogProps> = ({
  ticketID,
  open,
  closeDialog,
  kind,
}) => {
  const [body, setBody] = useState("");
  const backgroundColor = kind === "reply" ? "#1982FC" : "#FFB620";
  const color = kind === "reply" ? "white" : "black";
  const { fetcher } = useSWRConfig();
  const createArticle = async () => {
    await fetcher({
      document: updateTicketMutation,
      variables: {
        ticketId: `gid://zammad/Ticket/${ticketID}`,
        input: {
          article: {
            body,
            type: kind === "note" ? "note" : "phone",
            internal: kind === "note",
          },
        },
      },
    });
    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>
  );
};
