"use client";

import { FC } from "react";
import { useFormState } from "react-dom";
import { Grid } from "@mui/material";
import { Dialog, Button, TextField, Autocomplete } from "@link-stack/ui";
import { createTicketAction } from "app/_actions/tickets";
import useSWR from "swr";

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

export const TicketCreateDialog: FC<TicketCreateDialogProps> = ({
  open,
  closeDialog,
}) => {
  const initialState = {
    messages: [],
    errors: [],
    values: {
      customerId: "",
      groupId: "",
      ownerId: "",
      priorityId: "",
      stateId: "",
      tags: [],
      title: "",
      article: {
        body: "",
        type: "note",
        internal: true,
      },
    },
  };
  const [formState, formAction] = useFormState(
    createTicketAction,
    initialState,
  );
  const { data: users, error: usersError }: any = useSWR({
    url: "/api/v1/users",
    method: "GET",
  });
  const customers =
    users?.filter((user: any) => user.role_ids.includes(3)) ?? [];
  const formattedCustomers = customers.map((customer: any) => ({
    label: customer.login,
    id: `${customer.id}`,
  }));

  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>
          <Autocomplete
            name="customerId"
            label="Customer"
            options={formattedCustomers}
            formState={formState}
          />
        </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>
  );
};
