"use client";

import {
  useMemo,
  useRef,
  useState,
  type ReactNode,
  type SyntheticEvent,
} from "react";

import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
import FormatBoldRoundedIcon from "@mui/icons-material/FormatBoldRounded";
import FormatItalicRoundedIcon from "@mui/icons-material/FormatItalicRounded";
import FormatListBulletedRoundedIcon from "@mui/icons-material/FormatListBulletedRounded";
import FormatListNumberedRoundedIcon from "@mui/icons-material/FormatListNumberedRounded";
import FormatUnderlinedRoundedIcon from "@mui/icons-material/FormatUnderlinedRounded";
import LinkRoundedIcon from "@mui/icons-material/LinkRounded";
import RedoRoundedIcon from "@mui/icons-material/RedoRounded";
import SaveOutlinedIcon from "@mui/icons-material/SaveOutlined";
import UndoRoundedIcon from "@mui/icons-material/UndoRounded";

import Alert from "@mui/material/Alert";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import FormControl from "@mui/material/FormControl";
import FormHelperText from "@mui/material/FormHelperText";
import IconButton from "@mui/material/IconButton";
import MenuItem from "@mui/material/MenuItem";
import Select from "@mui/material/Select";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import {
  createCdcRgcDecision,
  type CreateCdcRgcDecisionPayload,
  type RgcDecisionLookupOption,
} from "../service/rgc-decision-service";

type CreateRgcDecisionDialogProps = {
  open: boolean;
  plenaries: RgcDecisionLookupOption[];
  ministries: RgcDecisionLookupOption[];
  categories: RgcDecisionLookupOption[];
  onClose: () => void;
  onCreated: () => Promise<void> | void;
};

type FormState = {
  plenaryId: string;
  stakeholderId: string;
  status: string;
  meetingDate: string;
  categoryId: string;
  focalPerson: string;
  verificationLink: string;
  decision: string;
  verificationSource: string;
};

type FormErrors = Partial<
  Record<keyof FormState, string>
>;

type TextFormat =
  | "bold"
  | "italic"
  | "underline"
  | "bullet"
  | "number"
  | "link";

const EMPTY_FORM: FormState = {
  plenaryId: "",
  stakeholderId: "",
  status: "",
  meetingDate: "",
  categoryId: "",
  focalPerson: "",
  verificationLink: "",
  decision: "",
  verificationSource: "",
};

const STATUS_OPTIONS = [
  {
    value: "NOT_ADDRESSED",
    label: "Not Addressed",
  },
  {
    value: "IN_PROGRESS",
    label: "In Progress",
  },
  {
    value: "SOLVED",
    label: "Solved",
  },
] as const;

function validateForm(
  form: FormState,
): FormErrors {
  const errors: FormErrors = {};

  if (!form.plenaryId) {
    errors.plenaryId =
      "Plenary is required.";
  }

  if (!form.stakeholderId) {
    errors.stakeholderId =
      "Ministry is required.";
  }

  if (!form.status) {
    errors.status =
      "Status is required.";
  }

  if (!form.meetingDate) {
    errors.meetingDate =
      "Meeting Date is required.";
  }

  if (!form.categoryId) {
    errors.categoryId =
      "Category is required.";
  }

  if (!form.focalPerson.trim()) {
    errors.focalPerson =
      "Focal Person is required.";
  }

  if (!form.verificationLink.trim()) {
    errors.verificationLink =
      "Verification Link is required.";
  }

  if (!form.decision.trim()) {
    errors.decision =
      "RGC Decision is required.";
  }

  if (!form.verificationSource.trim()) {
    errors.verificationSource =
      "Source of Verification is required.";
  }

  return errors;
}

function FieldLabel({
  children,
  required = false,
}: {
  children: ReactNode;
  required?: boolean;
}) {
  const theme = useTheme();

  return (
    <Typography
      component="label"
      sx={{
        display: "block",
        mb: 0.7,
        color:
          theme.palette.text.primary,
        fontSize: 12,
        fontWeight: 600,
        lineHeight: 1.4,
      }}
    >
      {children}

      {required ? (
        <Box
          component="span"
          sx={{
            ml: 0.35,
            color:
              theme.palette.error.main,
          }}
        >
          *
        </Box>
      ) : null}
    </Typography>
  );
}

type RichTextFieldProps = {
  label: string;
  value: string;
  placeholder: string;
  error?: string;
  onChange: (value: string) => void;
};

function RichTextField({
  label,
  value,
  placeholder,
  error,
  onChange,
}: RichTextFieldProps) {
  const theme = useTheme();

  const textareaRef =
    useRef<HTMLTextAreaElement | null>(
      null,
    );

  const historyRef =
    useRef<string[]>([""]);

  const historyIndexRef =
    useRef(0);

  const saveHistory = (
    nextValue: string,
  ) => {
    const history =
      historyRef.current.slice(
        0,
        historyIndexRef.current + 1,
      );

    if (
      history[history.length - 1] ===
      nextValue
    ) {
      return;
    }

    history.push(nextValue);

    historyRef.current =
      history.slice(-50);

    historyIndexRef.current =
      historyRef.current.length - 1;
  };

  const handleValueChange = (
    nextValue: string,
  ) => {
    onChange(nextValue);
    saveHistory(nextValue);
  };

  const updateSelection = (
    before: string,
    after = "",
    fallback = "",
  ) => {
    const textarea =
      textareaRef.current;

    if (!textarea) {
      return;
    }

    const start =
      textarea.selectionStart ?? 0;

    const end =
      textarea.selectionEnd ?? start;

    const selectedText =
      value.slice(start, end) ||
      fallback;

    const nextValue =
      value.slice(0, start) +
      before +
      selectedText +
      after +
      value.slice(end);

    handleValueChange(nextValue);

    window.requestAnimationFrame(
      () => {
        textarea.focus();

        const nextStart =
          start + before.length;

        textarea.setSelectionRange(
          nextStart,
          nextStart +
            selectedText.length,
        );
      },
    );
  };

  const applyFormat = (
    format: TextFormat,
  ) => {
    switch (format) {
      case "bold":
        updateSelection(
          "**",
          "**",
          "bold text",
        );
        break;

      case "italic":
        updateSelection(
          "*",
          "*",
          "italic text",
        );
        break;

      case "underline":
        updateSelection(
          "<u>",
          "</u>",
          "underlined text",
        );
        break;

      case "bullet":
        updateSelection(
          "• ",
          "",
          "List item",
        );
        break;

      case "number":
        updateSelection(
          "1. ",
          "",
          "List item",
        );
        break;

      case "link":
        updateSelection(
          "[",
          "](https://)",
          "link text",
        );
        break;
    }
  };

  const handleUndo = () => {
    if (
      historyIndexRef.current <= 0
    ) {
      return;
    }

    historyIndexRef.current -= 1;

    onChange(
      historyRef.current[
        historyIndexRef.current
      ] ?? "",
    );
  };

  const handleRedo = () => {
    if (
      historyIndexRef.current >=
      historyRef.current.length - 1
    ) {
      return;
    }

    historyIndexRef.current += 1;

    onChange(
      historyRef.current[
        historyIndexRef.current
      ] ?? "",
    );
  };

  const toolbarButtonSx = {
    width: 26,
    height: 26,
    minWidth: 26,
    p: 0,
    flexShrink: 0,
    borderRadius: "4px",
    color:
      theme.palette.text.secondary,

    "& svg": {
      fontSize: 14,
    },

    "&:hover": {
      color:
        theme.palette.primary.main,
      bgcolor: alpha(
        theme.palette.primary.main,
        0.08,
      ),
    },
  };

  return (
    <Box>
      <FieldLabel required>
        {label}
      </FieldLabel>

      <Box
        sx={{
          width: "100%",
          overflow: "hidden",
          borderRadius: "6px",
          border: `1px solid ${
            error
              ? theme.palette.error.main
              : theme.palette.divider
          }`,
          bgcolor:
            theme.palette.background
              .paper,

          "&:focus-within": {
            borderColor:
              theme.palette.primary.main,
            boxShadow: `0 0 0 1px ${alpha(
              theme.palette.primary.main,
              0.14,
            )}`,
          },
        }}
      >
        <Box
          sx={{
            width: "100%",
            minHeight: 38,
            px: 1,
            py: 0.6,

            display: "flex",
            alignItems: "center",
            gap: 0.25,

            overflowX: "auto",
            overflowY: "hidden",

            borderBottom: `1px solid ${theme.palette.divider}`,

            bgcolor:
              theme.palette.mode ===
              "dark"
                ? alpha(
                    theme.palette.common
                      .white,
                    0.015,
                  )
                : alpha(
                    theme.palette.common
                      .black,
                    0.012,
                  ),

            "&::-webkit-scrollbar": {
              height: 3,
            },

            "&::-webkit-scrollbar-thumb":
              {
                borderRadius: 99,
                bgcolor: alpha(
                  theme.palette.text
                    .secondary,
                  0.25,
                ),
              },

            "& input, & textarea, & select":
              {
                display:
                  "none !important",
              },
          }}
        >
          <IconButton
            type="button"
            aria-label="Undo"
            onClick={handleUndo}
            sx={toolbarButtonSx}
          >
            <UndoRoundedIcon />
          </IconButton>

          <IconButton
            type="button"
            aria-label="Redo"
            onClick={handleRedo}
            sx={toolbarButtonSx}
          >
            <RedoRoundedIcon />
          </IconButton>

          <Box
            aria-hidden
            sx={{
              width: 1,
              height: 18,
              mx: 0.5,
              flexShrink: 0,
              bgcolor:
                theme.palette.divider,
            }}
          />

          <IconButton
            type="button"
            aria-label="Bold"
            onClick={() =>
              applyFormat("bold")
            }
            sx={toolbarButtonSx}
          >
            <FormatBoldRoundedIcon />
          </IconButton>

          <IconButton
            type="button"
            aria-label="Italic"
            onClick={() =>
              applyFormat("italic")
            }
            sx={toolbarButtonSx}
          >
            <FormatItalicRoundedIcon />
          </IconButton>

          <IconButton
            type="button"
            aria-label="Underline"
            onClick={() =>
              applyFormat("underline")
            }
            sx={toolbarButtonSx}
          >
            <FormatUnderlinedRoundedIcon />
          </IconButton>

          <Box
            aria-hidden
            sx={{
              width: 1,
              height: 18,
              mx: 0.5,
              flexShrink: 0,
              bgcolor:
                theme.palette.divider,
            }}
          />

          <IconButton
            type="button"
            aria-label="Bulleted list"
            onClick={() =>
              applyFormat("bullet")
            }
            sx={toolbarButtonSx}
          >
            <FormatListBulletedRoundedIcon />
          </IconButton>

          <IconButton
            type="button"
            aria-label="Numbered list"
            onClick={() =>
              applyFormat("number")
            }
            sx={toolbarButtonSx}
          >
            <FormatListNumberedRoundedIcon />
          </IconButton>

          <IconButton
            type="button"
            aria-label="Insert link"
            onClick={() =>
              applyFormat("link")
            }
            sx={toolbarButtonSx}
          >
            <LinkRoundedIcon />
          </IconButton>
        </Box>

        <Box
          ref={textareaRef}
          component="textarea"
          value={value}
          placeholder={placeholder}
          onChange={(event) =>
            handleValueChange(
              event.target.value,
            )
          }
          sx={{
            display: "block",
            width: "100%",
            minHeight: 112,
            maxHeight: 190,

            px: 1.5,
            py: 1.25,

            resize: "vertical",

            border: 0,
            outline: 0,

            fontFamily: "inherit",
            fontSize: 12,
            fontWeight: 400,
            lineHeight: 1.55,

            color:
              theme.palette.text.primary,
            bgcolor: "transparent",

            "&::placeholder": {
              color:
                theme.palette.text
                  .secondary,
              opacity: 0.8,
            },

            "&::-webkit-scrollbar": {
              width: 6,
            },

            "&::-webkit-scrollbar-thumb":
              {
                borderRadius: 99,
                bgcolor: alpha(
                  theme.palette.text
                    .secondary,
                  0.25,
                ),
              },
          }}
        />
      </Box>

      {error ? (
        <FormHelperText
          error
          sx={{
            mx: 0,
            mt: 0.5,
            fontSize: 10,
          }}
        >
          {error}
        </FormHelperText>
      ) : null}
    </Box>
  );
}

export function CreateRgcDecisionDialog({
  open,
  plenaries,
  ministries,
  categories,
  onClose,
  onCreated,
}: CreateRgcDecisionDialogProps) {
  const theme = useTheme();

  const isDark =
    theme.palette.mode === "dark";

  const [form, setForm] =
    useState<FormState>(EMPTY_FORM);

  const [errors, setErrors] =
    useState<FormErrors>({});

  const [submitting, setSubmitting] =
    useState(false);

  const [
    submissionError,
    setSubmissionError,
  ] = useState<string | null>(null);

  const sortedPlenaries = useMemo(
    () =>
      [...plenaries].sort(
        (first, second) =>
          second.id - first.id,
      ),
    [plenaries],
  );

  const sortedMinistries = useMemo(
    () =>
      [...ministries].sort(
        (first, second) =>
          first.label.localeCompare(
            second.label,
          ),
      ),
    [ministries],
  );

  const sortedCategories = useMemo(
    () =>
      [...categories].sort(
        (first, second) =>
          first.label.localeCompare(
            second.label,
          ),
      ),
    [categories],
  );

  const resetForm = () => {
    setForm(EMPTY_FORM);
    setErrors({});
    setSubmissionError(null);
  };

  const handleClose = () => {
    if (submitting) {
      return;
    }

    resetForm();
    onClose();
  };

  const handleDialogClose = (
    _event: SyntheticEvent | object,
    reason:
      | "backdropClick"
      | "escapeKeyDown",
  ) => {
    if (submitting) {
      return;
    }

    if (reason === "backdropClick") {
      return;
    }

    handleClose();
  };

  const updateField = (
    key: keyof FormState,
    value: string,
  ) => {
    setForm((current) => ({
      ...current,
      [key]: value,
    }));

    setErrors((current) => {
      if (!current[key]) {
        return current;
      }

      const next = {
        ...current,
      };

      delete next[key];

      return next;
    });
  };

  const handleSubmit = async (
    saveAsDraft: boolean,
  ) => {
    const nextErrors =
      validateForm(form);

    setErrors(nextErrors);
    setSubmissionError(null);

    if (
      Object.keys(nextErrors).length >
      0
    ) {
      return;
    }

    const plenaryId = Number(
      form.plenaryId,
    );

    const stakeholderId = Number(
      form.stakeholderId,
    );

    const categoryId = Number(
      form.categoryId,
    );

    if (
      !Number.isInteger(plenaryId) ||
      plenaryId < 1
    ) {
      setErrors((current) => ({
        ...current,
        plenaryId:
          "Please select a valid Plenary.",
      }));

      return;
    }

    if (
      !Number.isInteger(
        stakeholderId,
      ) ||
      stakeholderId < 1
    ) {
      setErrors((current) => ({
        ...current,
        stakeholderId:
          "Please select a valid Ministry.",
      }));

      return;
    }

    if (
      !Number.isInteger(categoryId) ||
      categoryId < 1
    ) {
      setErrors((current) => ({
        ...current,
        categoryId:
          "Please select a valid Category.",
      }));

      return;
    }

    const payload: CreateCdcRgcDecisionPayload =
      {
        plenaryId,
        stakeholderId,
        categoryId,

        meetingDate:
          form.meetingDate,

        status:
          form.status,

        focalPerson:
          form.focalPerson.trim(),

        decision:
          form.decision.trim(),

        verificationSource:
          form.verificationSource.trim(),

        verificationLink:
          form.verificationLink.trim(),

      };

    try {
      setSubmitting(true);

      await createCdcRgcDecision(
        payload,
      );

      await onCreated();

      resetForm();
      onClose();
    } catch (requestError) {
      setSubmissionError(
        requestError instanceof Error
          ? requestError.message
          : "Unable to create RGC Decision.",
      );
    } finally {
      setSubmitting(false);
    }
  };

  const inputSx = {
    "& .MuiOutlinedInput-root": {
      height: 42,
      borderRadius: "6px",
      bgcolor:
        theme.palette.background.paper,
      fontSize: 12,

      "& fieldset": {
        borderColor:
          theme.palette.divider,
      },

      "&:hover fieldset": {
        borderColor:
          theme.palette.primary.main,
      },

      "&.Mui-focused fieldset": {
        borderColor:
          theme.palette.primary.main,
        borderWidth: 1,
      },
    },

    "& .MuiInputBase-input": {
      px: 1.5,
      py: 1.1,
      fontSize: 12,
    },

    "& .MuiInputBase-input::placeholder":
      {
        color:
          theme.palette.text.secondary,
        opacity: 0.8,
      },

    "& .MuiFormHelperText-root": {
      mx: 0,
      mt: 0.4,
      fontSize: 10,
    },
  };

  const selectSx = {
    height: 42,
    borderRadius: "6px",
    bgcolor:
      theme.palette.background.paper,
    fontSize: 12,

    "& .MuiOutlinedInput-notchedOutline":
      {
        borderColor:
          theme.palette.divider,
      },

    "&:hover .MuiOutlinedInput-notchedOutline":
      {
        borderColor:
          theme.palette.primary.main,
      },

    "&.Mui-focused .MuiOutlinedInput-notchedOutline":
      {
        borderColor:
          theme.palette.primary.main,
        borderWidth: 1,
      },

    "& .MuiSelect-select": {
      display: "flex",
      alignItems: "center",
      px: 1.5,
      py: 1,
    },
  };

  return (
    <Dialog
      open={open}
      onClose={handleDialogClose}
      maxWidth={false}
      sx={{
        "& .MuiDialog-container": {
          alignItems: "stretch",
          justifyContent: "flex-end",
        },

        "& .MuiDialog-paper": {
          width: {
            xs: "100vw",
            sm: 620,
          },

          minWidth: 0,
          maxWidth: "none",

          height: "100dvh",
          maxHeight: "100dvh",

          m: 0,

          display: "flex",
          flexDirection: "column",

          borderRadius: {
            xs: 0,
            sm: "12px 0 0 12px",
          },

          overflow: "hidden",

          bgcolor:
            theme.palette.background
              .paper,

          boxShadow: isDark
            ? "-12px 0 32px rgba(0,0,0,0.46)"
            : "-12px 0 32px rgba(15,23,42,0.18)",
        },
      }}
      slotProps={{
        backdrop: {
          sx: {
            bgcolor: isDark
              ? "rgba(0,0,0,0.72)"
              : "rgba(15,23,42,0.48)",
          },
        },
      }}
    >
      <DialogTitle
        component="div"
        sx={{
          minHeight: 66,
          px: 2,
          py: 1.1,

          display: "flex",
          alignItems: "center",
          justifyContent:
            "space-between",

          gap: 1.5,
          flexShrink: 0,

          borderBottom: `1px solid ${theme.palette.divider}`,

          bgcolor:
            theme.palette.background
              .paper,
        }}
      >
        <Typography
          sx={{
            minWidth: 0,
            color:
              theme.palette.text.primary,
            fontSize: 16,
            fontWeight: 700,
            lineHeight: 1.2,
            whiteSpace: "nowrap",
          }}
        >
          Create RGC Decision
        </Typography>

        <Stack
          direction="row"
          spacing={1}
          sx={{
            flexShrink: 0,
            alignItems: "center",
          }}
        >
          <Button
            type="button"
            variant="contained"
            disabled={submitting}
            startIcon={
              submitting ? (
                <CircularProgress
                  size={14}
                  color="inherit"
                />
              ) : (
                <SaveOutlinedIcon
                  sx={{
                    fontSize: 16,
                  }}
                />
              )
            }
            onClick={() =>
              void handleSubmit(true)
            }
            sx={{
              height: 42,
              px: 1.5,
              minWidth: 104,
              borderRadius: "6px",

              bgcolor:
                theme.palette.grey[400],

              color: "#FFFFFF",
              fontSize: 11,
              fontWeight: 600,
              textTransform: "none",

              boxShadow: "none",

              "&:hover": {
                bgcolor:
                  theme.palette.grey[500],
                boxShadow: "none",
              },
            }}
          >
            Save Draft
          </Button>

          <Button
            type="button"
            variant="contained"
            disabled={submitting}
            startIcon={
              submitting ? (
                <CircularProgress
                  size={14}
                  color="inherit"
                />
              ) : (
                <CheckRoundedIcon
                  sx={{
                    fontSize: 17,
                  }}
                />
              )
            }
            onClick={() =>
              void handleSubmit(false)
            }
            sx={{
              height: 42,
              px: 1.5,
              minWidth: 140,
              borderRadius: "6px",

              fontSize: 11,
              fontWeight: 600,
              textTransform: "none",

              boxShadow: "none",

              "&:hover": {
                boxShadow: "none",
              },
            }}
          >
            Send notification
          </Button>
        </Stack>
      </DialogTitle>

      <DialogContent
        sx={{
          flex: 1,
          minHeight: 0,

          px: 2,
          py: 2,

          overflowX: "hidden",
          overflowY: "auto",

          bgcolor:
            theme.palette.background
              .paper,

          "&::-webkit-scrollbar": {
            width: 6,
          },

          "&::-webkit-scrollbar-track":
            {
              bgcolor: "transparent",
            },

          "&::-webkit-scrollbar-thumb":
            {
              bgcolor: alpha(
                theme.palette.text
                  .secondary,
                0.3,
              ),
              borderRadius: 99,
            },
        }}
      >
        {submissionError ? (
          <Alert
            severity="error"
            sx={{
              mb: 1.5,
              fontSize: 11,
            }}
          >
            {submissionError}
          </Alert>
        ) : null}

        <Stack spacing={1.7}>
          <Box>
            <FieldLabel required>
              Plenary
            </FieldLabel>

            <FormControl
              fullWidth
              size="small"
              error={Boolean(
                errors.plenaryId,
              )}
            >
              <Select
                displayEmpty
                value={form.plenaryId}
                onChange={(event) =>
                  updateField(
                    "plenaryId",
                    String(
                      event.target.value,
                    ),
                  )
                }
                renderValue={(value) => {
                  if (!value) {
                    return (
                      <Typography
                        sx={{
                          color:
                            theme.palette.text
                              .secondary,
                          fontSize: 12,
                        }}
                      >
                        Select Plenary...
                      </Typography>
                    );
                  }

                  return (
                    sortedPlenaries.find(
                      (item) =>
                        String(item.id) ===
                        String(value),
                    )?.label ||
                    `Plenary #${value}`
                  );
                }}
                sx={selectSx}
              >
                {sortedPlenaries.length >
                0 ? (
                  sortedPlenaries.map(
                    (item) => (
                      <MenuItem
                        key={item.id}
                        value={String(
                          item.id,
                        )}
                        sx={{
                          fontSize: 12,
                        }}
                      >
                        {item.label}
                      </MenuItem>
                    ),
                  )
                ) : (
                  <MenuItem
                    disabled
                    sx={{
                      fontSize: 12,
                    }}
                  >
                    No plenaries found
                  </MenuItem>
                )}
              </Select>

              {errors.plenaryId ? (
                <FormHelperText>
                  {errors.plenaryId}
                </FormHelperText>
              ) : null}
            </FormControl>
          </Box>

          <Box>
            <FieldLabel required>
              Ministry
            </FieldLabel>

            <FormControl
              fullWidth
              size="small"
              error={Boolean(
                errors.stakeholderId,
              )}
            >
              <Select
                displayEmpty
                value={
                  form.stakeholderId
                }
                onChange={(event) =>
                  updateField(
                    "stakeholderId",
                    String(
                      event.target.value,
                    ),
                  )
                }
                renderValue={(value) => {
                  if (!value) {
                    return (
                      <Typography
                        sx={{
                          color:
                            theme.palette.text
                              .secondary,
                          fontSize: 12,
                        }}
                      >
                        Enter Ministry...
                      </Typography>
                    );
                  }

                  return (
                    sortedMinistries.find(
                      (item) =>
                        String(item.id) ===
                        String(value),
                    )?.label || ""
                  );
                }}
                sx={selectSx}
              >
                {sortedMinistries.length >
                0 ? (
                  sortedMinistries.map(
                    (item) => (
                      <MenuItem
                        key={item.id}
                        value={String(
                          item.id,
                        )}
                        sx={{
                          fontSize: 12,
                        }}
                      >
                        {item.label}
                      </MenuItem>
                    ),
                  )
                ) : (
                  <MenuItem
                    disabled
                    sx={{
                      fontSize: 12,
                    }}
                  >
                    No ministries found
                  </MenuItem>
                )}
              </Select>

              {errors.stakeholderId ? (
                <FormHelperText>
                  {errors.stakeholderId}
                </FormHelperText>
              ) : null}
            </FormControl>
          </Box>

          <Box>
            <FieldLabel required>
              Status
            </FieldLabel>

            <FormControl
              fullWidth
              size="small"
              error={Boolean(
                errors.status,
              )}
            >
              <Select
                displayEmpty
                value={form.status}
                onChange={(event) =>
                  updateField(
                    "status",
                    String(
                      event.target.value,
                    ),
                  )
                }
                renderValue={(value) => {
                  if (!value) {
                    return (
                      <Typography
                        sx={{
                          color:
                            theme.palette.text
                              .secondary,
                          fontSize: 12,
                        }}
                      >
                        Select Status
                      </Typography>
                    );
                  }

                  return (
                    STATUS_OPTIONS.find(
                      (item) =>
                        item.value === value,
                    )?.label || value
                  );
                }}
                sx={selectSx}
              >
                {STATUS_OPTIONS.map(
                  (item) => (
                    <MenuItem
                      key={item.value}
                      value={item.value}
                      sx={{
                        fontSize: 12,
                      }}
                    >
                      {item.label}
                    </MenuItem>
                  ),
                )}
              </Select>

              {errors.status ? (
                <FormHelperText>
                  {errors.status}
                </FormHelperText>
              ) : null}
            </FormControl>
          </Box>

          <Box
            sx={{
              display: "grid",
              gridTemplateColumns: {
                xs: "1fr",
                sm: "1fr 1fr",
              },
              gap: 1.25,
            }}
          >
            <Box>
              <FieldLabel required>
                Meeting Date
              </FieldLabel>

              <TextField
                fullWidth
                type="date"
                size="small"
                value={
                  form.meetingDate
                }
                error={Boolean(
                  errors.meetingDate,
                )}
                helperText={
                  errors.meetingDate
                }
                onChange={(event) =>
                  updateField(
                    "meetingDate",
                    event.target.value,
                  )
                }
                sx={inputSx}
              />
            </Box>

            <Box>
              <FieldLabel required>
                Category
              </FieldLabel>

              <FormControl
                fullWidth
                size="small"
                error={Boolean(
                  errors.categoryId,
                )}
              >
                <Select
                  displayEmpty
                  value={
                    form.categoryId
                  }
                  onChange={(event) =>
                    updateField(
                      "categoryId",
                      String(
                        event.target.value,
                      ),
                    )
                  }
                  renderValue={(value) => {
                    if (!value) {
                      return (
                        <Typography
                          sx={{
                            color:
                              theme.palette.text
                                .secondary,
                            fontSize: 12,
                          }}
                        >
                          Enter Category
                        </Typography>
                      );
                    }

                    return (
                      sortedCategories.find(
                        (item) =>
                          String(item.id) ===
                          String(value),
                      )?.label || ""
                    );
                  }}
                  sx={selectSx}
                >
                  {sortedCategories.length >
                  0 ? (
                    sortedCategories.map(
                      (item) => (
                        <MenuItem
                          key={item.id}
                          value={String(
                            item.id,
                          )}
                          sx={{
                            fontSize: 12,
                          }}
                        >
                          {item.label}
                        </MenuItem>
                      ),
                    )
                  ) : (
                    <MenuItem
                      disabled
                      sx={{
                        fontSize: 12,
                      }}
                    >
                      No categories found
                    </MenuItem>
                  )}
                </Select>

                {errors.categoryId ? (
                  <FormHelperText>
                    {errors.categoryId}
                  </FormHelperText>
                ) : null}
              </FormControl>
            </Box>
          </Box>

          <Box
            sx={{
              display: "grid",
              gridTemplateColumns: {
                xs: "1fr",
                sm: "1fr 1fr",
              },
              gap: 1.25,
            }}
          >
            <Box>
              <FieldLabel required>
                Focal Person (H.E)
              </FieldLabel>

              <TextField
                fullWidth
                size="small"
                placeholder="Enter Focal Person (H.E)..."
                value={
                  form.focalPerson
                }
                error={Boolean(
                  errors.focalPerson,
                )}
                helperText={
                  errors.focalPerson
                }
                onChange={(event) =>
                  updateField(
                    "focalPerson",
                    event.target.value,
                  )
                }
                sx={inputSx}
              />
            </Box>

            <Box>
              <FieldLabel required>
                Link to Verification Source
              </FieldLabel>

              <TextField
                fullWidth
                size="small"
                placeholder="Enter Link to Verification Source..."
                value={
                  form.verificationLink
                }
                error={Boolean(
                  errors.verificationLink,
                )}
                helperText={
                  errors.verificationLink
                }
                onChange={(event) =>
                  updateField(
                    "verificationLink",
                    event.target.value,
                  )
                }
                sx={inputSx}
              />
            </Box>
          </Box>

          <RichTextField
            label="RGC Decision"
            value={form.decision}
            placeholder="Enter RGC Decision..."
            error={errors.decision}
            onChange={(value) =>
              updateField(
                "decision",
                value,
              )
            }
          />

          <RichTextField
            label="Source of Verification"
            value={
              form.verificationSource
            }
            placeholder="Enter Source of Verification..."
            error={
              errors.verificationSource
            }
            onChange={(value) =>
              updateField(
                "verificationSource",
                value,
              )
            }
          />

          <Box sx={{ height: 6 }} />
        </Stack>
      </DialogContent>
    </Dialog>
  );
}

export default CreateRgcDecisionDialog;