"use client";

import { FC, useEffect, useState } from "react";
import { Grid, Box } from "@mui/material";
import { Select, Button } from "@link-stack/ui";
import { MuiChipsInput } from "mui-chips-input";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import {
  updateTicketAction,
  getTicketAction,
  getTicketStatesAction,
  getTicketPrioritiesAction,
} from "app/_actions/tickets";
import { getAgentsAction } from "app/_actions/users";
import { getGroupsAction } from "app/_actions/groups";

interface TicketEditProps {
  id: string;
}

export const TicketEdit: FC<TicketEditProps> = ({ id }) => {
  const [ticket, setTicket] = useState<any>();
  const [hasChanges, setHasChanges] = useState(false);
  const [formState, setFormState] = useState({
    values: {
      group: null,
      owner: null,
      priority: null,
      pendingTime: null,
      state: null,
      tags: [],
    },
  });
  const [ticketStates, setTicketStates] = useState<any>();
  const [ticketPriorities, setTicketPriorities] = useState<any>();
  const [groups, setGroups] = useState<any>();
  const [agents, setAgents] = useState<any>();
  const [pendingVisible, setPendingVisible] = useState(false);

  const filteredStates =
    ticketStates?.filter(
      (state: any) => !["new", "merged", "removed"].includes(state.label),
    ) ?? [];

  useEffect(() => {
    const fetchAgents = async () => {
      const result = await getAgentsAction();
      setAgents(result);
    };

    const fetchGroups = async () => {
      const result = await getGroupsAction();
      setGroups(result);
    };

    const fetchTicketStates = async () => {
      const result = await getTicketStatesAction();
      setTicketStates(result);
    };

    const fetchTicketPriorities = async () => {
      const result = await getTicketPrioritiesAction();
      setTicketPriorities(result);
    };

    fetchTicketStates();
    fetchTicketPriorities();
    fetchAgents();
    fetchGroups();
  }, []);

  useEffect(() => {
    const fetchTicket = async () => {
      const result = await getTicketAction(id);
      setTicket(result);
      setFormState({
        values: {
          ...formState.values,
          group: result?.group?.id,
          owner: result?.owner?.id,
          priority: result?.priority?.id,
          state: result?.state?.id,
          tags: result?.tags,
        },
      });
    };

    fetchTicket();
  }, []);

  const updateFormState = (name: string, value: any) => {
    setFormState({
      values: {
        ...formState.values,
        [name]: value,
      },
    });
    const stateName = filteredStates?.find(
      (state: any) => state.id === formState.values.state,
    )?.name;
    setPendingVisible(stateName?.includes("pending") ?? false);
    setHasChanges(true);
  };

  const updateTicket = async () => {
    await updateTicketAction(id, formState.values);
    setHasChanges(false);
  };

  const shouldRender = !!ticket;

  return (
    <Box sx={{ height: "100vh", background: "#ddd", p: 2 }}>
      {shouldRender && (
        <Grid container direction="column" spacing={3}>
          <Grid item>
            <Box sx={{ m: 1 }}>Group</Box>
            <Select
              name="group"
              label="Group"
              formState={formState}
              updateFormState={updateFormState}
              getOptions={() => groups}
            />
          </Grid>
          <Grid item>
            <Box sx={{ m: 1, mt: 0 }}>Owner</Box>
            <Select
              name="owner"
              label="Owner"
              formState={formState}
              updateFormState={updateFormState}
              getOptions={() => agents}
            />
          </Grid>
          <Grid item xs={12}>
            <Box sx={{ m: 1, mt: 0 }}>State</Box>
            <Select
              name="state"
              label="State"
              formState={formState}
              updateFormState={updateFormState}
              getOptions={() => filteredStates}
            />
          </Grid>
          <Grid
            item
            xs={12}
            sx={{ display: pendingVisible ? "inherit" : "none" }}
          >
            <DatePicker
              label="Pending Date"
              value={new Date(formState.values.pendingTime)}
              onChange={(newValue: any) => {
                updateFormState("pendingDate", 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}
              updateFormState={updateFormState}
              getOptions={() => ticketPriorities}
            />
          </Grid>
          <Grid item>
            <Box sx={{ mb: 1 }}>Tags</Box>
            <MuiChipsInput
              sx={{ backgroundColor: "white", width: "100%" }}
              value={formState.values.tags}
              hideClearAll
              onChange={(tags: any) => {
                updateFormState("tags", tags);
              }}
              onDeleteChip={(tag: any) => {
                const tags = formState.values.tags.filter(
                  (t: any) => t !== tag,
                );
                updateFormState("tags", tags);
              }}
            />
          </Grid>
          <Grid item container direction="row-reverse">
            <Grid item>
              <Button
                text="Save"
                kind="primary"
                onClick={updateTicket}
                disabled={!hasChanges}
              />
            </Grid>
          </Grid>
        </Grid>
      )}
    </Box>
  );
};
