"use client";

import { FC, useEffect, useState } from "react";
import {
  Grid,
  Box,
  // Typography,
  // TextField,
  Stack,
  Select,
  MenuItem,
} from "@mui/material";
import { MuiChipsInput } from "mui-chips-input";
import useSWR, { useSWRConfig } from "swr";
import { getTicketQuery } from "app/_graphql/getTicketQuery";
import { updateTicketMutation } from "app/_graphql/updateTicketMutation";
import "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";

interface TicketEditProps {
  id: string;
}

export const TicketEdit: FC<TicketEditProps> = ({ id }) => {
  const [selectedGroup, setSelectedGroup] = useState("");
  const [selectedOwner, setSelectedOwner] = useState("");
  const [selectedPriority, setSelectedPriority] = useState("");
  const [selectedState, setSelectedState] = useState("");
  const [selectedTags, setSelectedTags] = useState([]);
  const handleDelete = () => {
    console.info("You clicked the delete icon.");
  };
  const restFetcher = (url: string) => fetch(url).then((r) => r.json());

  const { data: groups } = useSWR("/api/v1/groups", restFetcher);
  const { data: users } = useSWR("/api/v1/users", restFetcher);
  const { data: states } = useSWR("/api/v1/ticket_states", restFetcher);
  const { data: priorities } = useSWR("/api/v1/ticket_priorities", restFetcher);
  const { data: tags } = useSWR("/api/v1/tags", restFetcher);

  const { fetcher } = useSWRConfig();
  const { data: ticketData, error: ticketError }: any = useSWR(
    {
      document: getTicketQuery,
      variables: { ticketId: `gid://zammad/Ticket/${id}` },
    },
    { refreshInterval: 100000 }
  );
  useEffect(() => {
    const ticket = ticketData?.ticket;
    if (ticket) {
      const groupID = ticket.group.id?.split("/").pop();
      setSelectedGroup(groupID);
      const ownerID = ticket.owner.id?.split("/").pop();
      setSelectedOwner(ownerID);
      const priorityID = ticket.priority.id?.split("/").pop();
      setSelectedPriority(priorityID);
      const stateID = ticket.state.id?.split("/").pop();
      setSelectedState(stateID);
      setSelectedTags(ticket.tags);
    }
  }, [ticketData, ticketError]);
  const updateTicket = async () => {
    const input = {
      ownerId: `gid://zammad/User/${selectedOwner}`,
      priorityId: `gid://zammad/Ticket::Priority/${selectedPriority}`,
      stateId: `gid://zammad/Ticket::State/${selectedState}`,
      groupId: `gid://zammad/Group/${selectedGroup}`,
      // tags: selectedTags,
    };
    const res = await fetcher({
      document: updateTicketMutation,
      variables: {
        ticketId: `gid://zammad/Ticket/${id}`,
        input,
      },
    });
    console.log({ res });
  };
  const shouldRender = ticketData && !ticketError;

  return (
    shouldRender && (
      <Box sx={{ height: "100vh", background: "#ddd", p: 2 }}>
        <Grid container direction="column" spacing={3}>
          <Grid item>
            <Box sx={{ m: 1 }}>Group</Box>
            <Select
              defaultValue={selectedGroup}
              value={selectedGroup}
              onChange={(e: any) => {
                setSelectedGroup(e.target.value);
                updateTicket();
              }}
              size="small"
              sx={{
                width: "100%",
                backgroundColor: "white",
              }}
            >
              {groups?.map((group: any) => (
                <MenuItem key={group.id} value={`${group.id}`}>
                  {group.name}
                </MenuItem>
              ))}
            </Select>
          </Grid>
          <Grid item>
            <Box sx={{ m: 1, mt: 0 }}>Owner</Box>
            <Select
              value={selectedOwner}
              onChange={(e: any) => {
                setSelectedOwner(e.target.value);
                updateTicket();
              }}
              size="small"
              sx={{
                width: "100%",
                backgroundColor: "white",
              }}
            >
              {users?.map((user: any) => (
                <MenuItem key={user.id} value={user.id}>
                  {user.firstname} {user.lastname}
                </MenuItem>
              ))}
            </Select>
          </Grid>
          <Grid item>
            <Box sx={{ m: 1, mt: 0 }}>State</Box>
            <Select
              value={selectedState}
              onChange={(e: any) => {
                setSelectedState(e.target.value);
                updateTicket();
              }}
              size="small"
              sx={{
                width: "100%",
                backgroundColor: "white",
              }}
            >
              {states?.map((state: any) => (
                <MenuItem key={state.id} value={state.id}>
                  {state.name}
                </MenuItem>
              ))}
            </Select>
          </Grid>
          <Grid item>
            <Box sx={{ m: 1, mt: 0 }}>Priority</Box>
            <Select
              value={selectedPriority}
              onChange={(e: any) => {
                setSelectedPriority(e.target.value);
                updateTicket();
              }}
              size="small"
              sx={{
                width: "100%",
                backgroundColor: "white",
              }}
            >
              {priorities?.map((priority: any) => (
                <MenuItem key={priority.id} value={priority.id}>
                  {priority.name}
                </MenuItem>
              ))}
            </Select>
          </Grid>

          <Grid item>
            <Box sx={{ mb: 1 }}>Tags</Box>
            <MuiChipsInput
              sx={{ backgroundColor: "white", width: "100%" }}
              value={selectedTags}
              onChange={(tags: any) => {
                setSelectedTags(tags);
                updateTicket();
              }}
            />
          </Grid>
        </Grid>
      </Box>
    )
  );
};
