"use client";

import { FC, useState, useEffect, useActionState } from "react";
import { useRouter } from "next/navigation";
import { Grid } from "@mui/material";
import {
  Dialog,
  Button,
  TextField,
  Autocomplete,
  Select,
} from "@link-stack/ui";
import { createTicketAction } from "app/_actions/tickets";
import { getCustomersAction } from "app/_actions/users";
import { getGroupsAction } from "app/_actions/groups";

interface TicketCreateDialogProps {
  open: boolean;
  closeDialog: () => void;
}

export const TicketCreateDialog: FC<TicketCreateDialogProps> = ({
  open,
  closeDialog,
}) => {
  const [customers, setCustomers] = useState([]);
  const [groups, setGroups] = useState([]);
  const initialState = {
    messages: [],
    errors: [],
    values: {
      customerId: "",
      groupId: "",
      ownerId: "",
      priorityId: "",
      stateId: "",
      tags: [],
      title: "",
      article: {
        body: "",
        type: "note",
        internal: true,
      },
    },
  };
  const [formState, formAction] = useActionState(
    createTicketAction,
    initialState,
  );
  const [liveFormState, setLiveFormState] = useState(formState);
  const updateFormState = (field: string, value: any) => {
    const newState = { ...liveFormState };
    newState.values[field] = value;
    setLiveFormState(newState);
  };

  useEffect(() => {
    const fetchUsers = async () => {
      const result = await getCustomersAction();
      setCustomers(result);
    };

    fetchUsers();
  }, []);

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

    fetchGroups();
  }, []);

  const router = useRouter();

  useEffect(() => {
    if (formState.success) {
      closeDialog();
    }
  }, [formState.success, router]);

  return (
    <Dialog
      title="Create Ticket"
      open={open}
      onClose={closeDialog}
      formAction={formAction}
      buttons={
        <Grid container justifyContent="space-between">
          <Grid item>
            <Button
              text="Cancel"
              kind="secondary"
              onClick={() => {
                closeDialog();
              }}
            />
          </Grid>
          <Grid item>
            <Button text="Save" type="submit" kind="primary" />
          </Grid>
        </Grid>
      }
    >
      <Grid container direction="column" spacing={3}>
        <Grid item>
          <Select
            name="groupId"
            label="Group"
            getOptions={() => groups as any}
            formState={liveFormState}
            updateFormState={updateFormState}
          />
        </Grid>
        <Grid item>
          <Select
            name="customerId"
            label="Customer"
            getOptions={() => customers as any}
            formState={liveFormState}
            updateFormState={updateFormState}
          />
        </Grid>
        <Grid item>
          <TextField name="title" label="Title" formState={formState} />
        </Grid>
        <Grid item>
          <TextField
            name="details"
            label="Details"
            lines={10}
            formState={formState}
          />
        </Grid>
      </Grid>
    </Dialog>
  );
};
