"use client";

import { FC, useEffect, useState } from "react";
import { Grid, Box, MenuItem } from "@mui/material";
import { useFormState } from "react-dom";
import { Select, Button } from "@link-stack/ui";
import { MuiChipsInput } from "mui-chips-input";
import useSWR, { useSWRConfig } from "swr";
import { getTicketQuery } from "app/_graphql/getTicketQuery";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { updateTicketAction } from "app/_actions/tickets";

interface TicketEditProps {
  id: string;
}

export const TicketEdit: FC<TicketEditProps> = ({ id }) => {
  const selectedTags = [];
  const pendingVisible = false;
  const pendingDate = new Date();
  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: recent } = useSWR("/api/v1/recent_view", restFetcher);

  // const { data: tags } = useSWR("/api/v1/tags", restFetcher);
  const filteredStates = states?.filter(
    (state: any) => !["new", "merged", "removed"].includes(state.name),
  );
  const agents = users?.filter((user: any) => user.role_ids.includes(2)) ?? [];
  const { fetcher } = useSWRConfig();
  const { data: ticketData, error: ticketError }: any = useSWR(
    {
      document: getTicketQuery,
      variables: { ticketId: `gid://zammad/Ticket/${id}` },
    },
    { refreshInterval: 10000 },
  );
  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]);

  /*
  useEffect(() => {

    const stateName = filteredStates?.find(
      (state: any) => state.id === selectedState,
    )?.name;
    setPendingVisible(stateName?.includes("pending") ?? false);
  }, [selectedState]);
   */
  const updateTicket = async (input: any) => {
    /*
    console.log({ input });
    const res = await fetcher({
      document: updateTicketMutation,
      variables: {
        ticketId: `gid://zammad/Ticket/${id}`,
        input,
      },
    });
    console.log({ res });
     */
  };
  const updateTags = async (tags: string[]) => {
    /*
    console.log({ tags });
    const res = await fetcher({
      document: updateTagsMutation,
      variables: {
        objectId: `gid://zammad/Ticket/${id}`,
        tags,
      },
    });
    console.log({ res });
     */
  };
  const initialState = {
    messages: [],
    errors: [],
    values: {
      customer: "",
      group: "",
      owner: "",
      priority: "",
      state: "",
      tags: [],
      title: "",
      article: {
        body: "",
        type: "note",
        internal: true,
      },
    },
  };
  const [formState, formAction] = useFormState(
    updateTicketAction,
    initialState,
  );
  const shouldRender = ticketData && !ticketError;

  return (
    shouldRender && (
      <Box sx={{ height: "100vh", background: "#ddd", p: 2 }}>
        <form action={formAction}>
          <Grid container direction="column" spacing={3}>
            <Grid item>
              <Box sx={{ m: 1 }}>Group</Box>
              <Select
                name="group"
                label="Group"
                formState={formState}
                getOptions={() =>
                  groups?.map((group: any) => ({
                    value: group.id,
                    label: group.name,
                  })) ?? []
                }
                /*
                onChange={(e: any) => {
                  const newGroup = e.target.value;
                  setSelectedGroup(newGroup);
                  updateTicket({
                    groupId: `gid://zammad/Group/${newGroup}`,
                  });
                }}
                 */
              />
            </Grid>
            <Grid item>
              <Box sx={{ m: 1, mt: 0 }}>Owner</Box>
              <Select
                name="owner"
                label="Owner"
                formState={formState}
                getOptions={() =>
                  agents?.map((user: any) => ({
                    value: user.id,
                    label: `${user.firstname} ${user.lastname}`,
                  })) ?? []
                }
                /*
                onChange={(e: any) => {
                  const newOwner = e.target.value;
                  setSelectedOwner(newOwner);
                  updateTicket({ ownerId: `gid://zammad/User/${newOwner}` });
                }}
                 */
              />
            </Grid>
            <Grid item xs={12}>
              <Box sx={{ m: 1, mt: 0 }}>State</Box>
              <Select
                name="state"
                label="State"
                formState={formState}
                getOptions={() =>
                  filteredStates?.map((state: any) => ({
                    value: state.id,
                    label: state.name,
                  })) ?? []
                }
                /*
                onChange={(e: any) => {
                  const newState = e.target.value;
                  setSelectedState(newState);
                  updateTicket({
                    stateId: `gid://zammad/Ticket::State/${newState}`,
                    pendingTime: pendingDate.toISOString(),
                  });
                }}
                 */
              />
            </Grid>
            <Grid
              item
              xs={12}
              sx={{ display: pendingVisible ? "inherit" : "none" }}
            >
              {/*  <DatePicker
                label="Pending Date"
                value={pendingDate}
                onChange={(newValue: any) => {

                  console.log(newValue);
                  setPendingDate(newValue);
                  updateTicket({
                    pendingTime: newValue.toISOString(),
                  })

                }}
                slotProps={{ textField: { size: "small" } }}
                sx={{
                  width: "100%",
                  backgroundColor: "white",
                }}
              /> */}
            </Grid>
            <Grid item>
              <Box sx={{ m: 1, mt: 0 }}>Priority</Box>
              <Select
                name="priority"
                label="Priority"
                formState={formState}
                getOptions={() =>
                  priorities?.map((priority: any) => ({
                    value: priority.id,
                    label: priority.name,
                  })) ?? []
                }
                /*
                onChange={(e: any) => {

                  const newPriority = e.target.value;
                  setSelectedPriority(newPriority);
                  updateTicket({
                    priorityId: `gid://zammad/Ticket::Priority/${newPriority}`,
                  });

                }}
                                   */
              />
            </Grid>

            <Grid item>
              <Box sx={{ mb: 1 }}>Tags</Box>
              <MuiChipsInput
                sx={{ backgroundColor: "white", width: "100%" }}
                value={selectedTags}
                onChange={(tags: any) => {
                  /*
                  setSelectedTags(tags);
                  updateTags(tags);
                   */
                }}
              />
            </Grid>
            <Grid item container direction="row-reverse">
              <Grid item>
                <Button text="Save" kind="primary" type="submit" />
              </Grid>
            </Grid>
          </Grid>
        </form>
      </Box>
    )
  );
};
