"use client";

import { useEffect, useState, type ChangeEvent, type MouseEvent } from "react";

import AccessTimeOutlinedIcon from "@mui/icons-material/AccessTimeOutlined";
import AttachFileOutlinedIcon from "@mui/icons-material/AttachFileOutlined";
import CloudUploadOutlinedIcon from "@mui/icons-material/CloudUploadOutlined";
import ExpandLessOutlinedIcon from "@mui/icons-material/ExpandLessOutlined";
import ExpandMoreOutlinedIcon from "@mui/icons-material/ExpandMoreOutlined";
import FilePresentOutlinedIcon from "@mui/icons-material/FilePresentOutlined";
import KeyboardArrowDownRoundedIcon from "@mui/icons-material/KeyboardArrowDownRounded";
import KeyboardArrowUpRoundedIcon from "@mui/icons-material/KeyboardArrowUpRounded";
import PersonOutlineOutlinedIcon from "@mui/icons-material/PersonOutlineOutlined";
import Alert from "@mui/material/Alert";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Checkbox from "@mui/material/Checkbox";
import CircularProgress from "@mui/material/CircularProgress";
import Dialog from "@mui/material/Dialog";
import InputAdornment from "@mui/material/InputAdornment";
import Popover from "@mui/material/Popover";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import type { PlenaryMinistryApi } from "../plenary-data";
import {
  createPlenary,
  getActiveMinistries,
  uploadPlenaryDocument,
} from "../service/plenary-service";

type Props = {
  open: boolean;
  onClose: () => void;
  onCreated: () => void;
};

type SubmitStatus = "Draft" | "Sent";
type TimeMeridiem = "AM" | "PM";

type TimeSelectFieldProps = {
  value: string;
  onChange: (value: string) => void;
  disabled?: boolean;
};

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001/api/v1";

const BACKEND_ORIGIN = API_BASE_URL.replace(/\/api\/v1\/?$/, "");

function getErrorMessage(error: unknown): string {
  if (error instanceof Error && error.message.trim()) {
    return error.message;
  }

  return "Something went wrong. Please try again.";
}

function getMinistryLogoUrl(
  logo: string | null | undefined,
): string | undefined {
  if (!logo) {
    return undefined;
  }

  if (logo.startsWith("http://") || logo.startsWith("https://")) {
    return logo;
  }

  return `${BACKEND_ORIGIN}${logo.startsWith("/") ? "" : "/"}${logo}`;
}

function padTimePart(value: number): string {
  return String(value).padStart(2, "0");
}

function getTimeParts(value: string): {
  hour: number;
  minute: number;
  meridiem: TimeMeridiem;
} {
  const [hoursText, minutesText] = value.split(":");

  const hours = Number(hoursText);
  const minutes = Number(minutesText);

  if (
    !Number.isInteger(hours) ||
    !Number.isInteger(minutes) ||
    hours < 0 ||
    hours > 23 ||
    minutes < 0 ||
    minutes > 59
  ) {
    return {
      hour: 12,
      minute: 0,
      meridiem: "PM",
    };
  }

  return {
    hour: hours % 12 || 12,
    minute: minutes,
    meridiem: hours >= 12 ? "PM" : "AM",
  };
}

function formatTimeLabel(value: string): string {
  const { hour, minute, meridiem } = getTimeParts(value);

  return `${hour}:${padTimePart(minute)} ${meridiem}`;
}

function toTwentyFourHourTime(
  hour: number,
  minute: number,
  meridiem: TimeMeridiem,
): string {
  let hours = hour % 12;

  if (meridiem === "PM") {
    hours += 12;
  }

  return `${padTimePart(hours)}:${padTimePart(minute)}`;
}

function toIsoDateTime(dateValue: string, timeValue: string): string {
  const date = new Date(`${dateValue}T${timeValue}:00`);

  if (Number.isNaN(date.getTime())) {
    throw new Error("Please select a valid date and time.");
  }

  return date.toISOString();
}

function TimeSelectField({
  value,
  onChange,
  disabled = false,
}: TimeSelectFieldProps) {
  const theme = useTheme();

  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  const [draftHour, setDraftHour] = useState(12);
  const [draftMinute, setDraftMinute] = useState(0);
  const [draftMeridiem, setDraftMeridiem] = useState<TimeMeridiem>("PM");

  const open = Boolean(anchorEl);

  function openPicker(event: MouseEvent<HTMLElement>) {
    if (disabled) {
      return;
    }

    const time = getTimeParts(value);

    setDraftHour(time.hour);
    setDraftMinute(time.minute);
    setDraftMeridiem(time.meridiem);
    setAnchorEl(event.currentTarget);
  }

  function closePicker() {
    setAnchorEl(null);
  }

  function changeHour(amount: number) {
    setDraftHour((current) => {
      return ((current - 1 + amount + 12) % 12) + 1;
    });
  }

  function changeMinute(amount: number) {
    setDraftMinute((current) => {
      return (current + amount + 60) % 60;
    });
  }

  function toggleMeridiem() {
    setDraftMeridiem((current) => {
      return current === "AM" ? "PM" : "AM";
    });
  }

  function confirmTime() {
    onChange(toTwentyFourHourTime(draftHour, draftMinute, draftMeridiem));

    closePicker();
  }

  const arrowButtonSx = {
    minWidth: 34,
    width: 34,
    height: 26,
    p: 0,
    color: theme.palette.text.primary,
    borderRadius: "8px",
    "&:hover": {
      bgcolor: alpha(theme.palette.primary.main, 0.09),
    },
  };

  return (
    <>
      <Box
        role="button"
        tabIndex={disabled ? -1 : 0}
        onClick={openPicker}
        onKeyDown={(event) => {
          if (disabled) {
            return;
          }

          if (event.key === "Enter" || event.key === " ") {
            event.preventDefault();
            event.currentTarget.click();
          }
        }}
        sx={{
          height: 45,
          px: 1.75,
          display: "flex",
          alignItems: "center",
          gap: 1.2,
          border: `1px solid ${alpha(theme.palette.text.primary, 0.22)}`,
          borderRadius: "11px",
          bgcolor: theme.palette.background.paper,
          color: value
            ? theme.palette.text.primary
            : theme.palette.text.secondary,
          cursor: disabled ? "not-allowed" : "pointer",
          userSelect: "none",
          transition: "border-color 0.2s ease, box-shadow 0.2s ease",
          "&:hover": disabled
            ? undefined
            : {
                borderColor: alpha(theme.palette.text.primary, 0.36),
              },
          "&:focus-visible": {
            outline: "none",
            borderColor: theme.palette.primary.main,
            boxShadow: `0 0 0 3px ${alpha(theme.palette.primary.main, 0.18)}`,
          },
        }}
      >
        <AccessTimeOutlinedIcon
          sx={{
            fontSize: 21,
            color: theme.palette.text.secondary,
          }}
        />

        <Typography
          component="span"
          sx={{
            fontSize: 16,
            lineHeight: 1,
            color: value
              ? theme.palette.text.primary
              : theme.palette.text.secondary,
            whiteSpace: "nowrap",
          }}
        >
          {value ? formatTimeLabel(value) : "Select time"}
        </Typography>
      </Box>

      <Popover
        open={open}
        anchorEl={anchorEl}
        onClose={closePicker}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "left",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
        slotProps={{
          paper: {
            sx: {
              mt: 1,
              width: 322,
              maxWidth: "calc(100vw - 32px)",
              borderRadius: "18px",
              overflow: "hidden",
              bgcolor: theme.palette.background.paper,
              color: theme.palette.text.primary,
              boxShadow:
                "0 14px 32px rgba(0, 0, 0, 0.18), 0 3px 8px rgba(0, 0, 0, 0.09)",
            },
          },
        }}
      >
        <Box sx={{ px: 3, pt: 2.25, pb: 2 }}>
          <Box
            sx={{
              display: "grid",
              gridTemplateColumns: "1fr 22px 1fr 1.25fr",
              alignItems: "center",
              columnGap: 1,
            }}
          >
            <Box
              sx={{
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
              }}
            >
              <Button
                type="button"
                onClick={() => changeHour(1)}
                sx={arrowButtonSx}
              >
                <KeyboardArrowUpRoundedIcon />
              </Button>

              <Typography
                sx={{
                  minWidth: 42,
                  py: 0.6,
                  textAlign: "center",
                  fontSize: 23,
                  fontWeight: 500,
                }}
              >
                {draftHour}
              </Typography>

              <Button
                type="button"
                onClick={() => changeHour(-1)}
                sx={arrowButtonSx}
              >
                <KeyboardArrowDownRoundedIcon />
              </Button>
            </Box>

            <Typography
              sx={{
                pb: 0.4,
                fontSize: 26,
                fontWeight: 500,
                textAlign: "center",
              }}
            >
              :
            </Typography>

            <Box
              sx={{
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
              }}
            >
              <Button
                type="button"
                onClick={() => changeMinute(1)}
                sx={arrowButtonSx}
              >
                <KeyboardArrowUpRoundedIcon />
              </Button>

              <Typography
                sx={{
                  minWidth: 48,
                  py: 0.6,
                  textAlign: "center",
                  fontSize: 23,
                  fontWeight: 500,
                }}
              >
                {padTimePart(draftMinute)}
              </Typography>

              <Button
                type="button"
                onClick={() => changeMinute(-1)}
                sx={arrowButtonSx}
              >
                <KeyboardArrowDownRoundedIcon />
              </Button>
            </Box>

            <Button
              type="button"
              onClick={toggleMeridiem}
              sx={{
                minWidth: 62,
                alignSelf: "center",
                justifySelf: "center",
                borderRadius: "8px",
                color: theme.palette.text.primary,
                fontSize: 22,
                fontWeight: 500,
                textTransform: "uppercase",
                "&:hover": {
                  bgcolor: alpha(theme.palette.primary.main, 0.09),
                },
              }}
            >
              {draftMeridiem}
            </Button>
          </Box>

          <Box
            sx={{
              mt: 2.2,
              pt: 1.2,
              display: "flex",
              justifyContent: "center",
              gap: 1.2,
              borderTop: `1px solid ${alpha(theme.palette.text.primary, 0.08)}`,
            }}
          >
            <Button
              type="button"
              variant="outlined"
              onClick={closePicker}
              sx={{
                minWidth: 108,
                height: 36,
                borderRadius: "8px",
                borderColor: alpha(theme.palette.text.primary, 0.25),
                color: theme.palette.text.primary,
                fontWeight: 700,
                textTransform: "none",
              }}
            >
              Cancel
            </Button>

            <Button
              type="button"
              variant="contained"
              onClick={confirmTime}
              sx={{
                minWidth: 108,
                height: 36,
                borderRadius: "8px",
                fontWeight: 800,
                textTransform: "none",
                boxShadow: "none",
              }}
            >
              Confirm
            </Button>
          </Box>
        </Box>
      </Popover>
    </>
  );
}

export function PlenaryCreateDialog({ open, onClose, onCreated }: Props) {
  const theme = useTheme();

  const [name, setName] = useState("");

  const [meetingDate, setMeetingDate] = useState("");
  const [meetingTime, setMeetingTime] = useState("");

  const [deadline, setDeadline] = useState("");
  const [deadlineTime, setDeadlineTime] = useState("");

  const [selectedMinistryIds, setSelectedMinistryIds] = useState<number[]>([]);

  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [ministries, setMinistries] = useState<PlenaryMinistryApi[]>([]);
  const [openMinistry, setOpenMinistry] = useState(true);
  const [loadingMinistries, setLoadingMinistries] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!open) {
      return;
    }

    let cancelled = false;

    async function loadMinistries() {
      setLoadingMinistries(true);
      setError("");

      try {
        const items = await getActiveMinistries();

        if (!cancelled) {
          setMinistries(items);
          setSelectedMinistryIds([]);
        }
      } catch (loadError: unknown) {
        if (!cancelled) {
          setMinistries([]);
          setError(getErrorMessage(loadError));
        }
      } finally {
        if (!cancelled) {
          setLoadingMinistries(false);
        }
      }
    }

    void loadMinistries();

    return () => {
      cancelled = true;
    };
  }, [open]);

  function resetForm() {
    setName("");

    setMeetingDate("");
    setMeetingTime("");

    setDeadline("");
    setDeadlineTime("");

    setSelectedMinistryIds([]);
    setUploadedFile(null);
    setError("");
    setOpenMinistry(true);
  }

  function handleClose() {
    if (saving) {
      return;
    }

    resetForm();
    onClose();
  }

  function toggleMinistry(ministryId: number) {
    setSelectedMinistryIds((previous) =>
      previous.includes(ministryId)
        ? previous.filter((id) => id !== ministryId)
        : [...previous, ministryId],
    );
  }

  function handleFileChange(event: ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];

    if (!file) {
      return;
    }

    if (file.type !== "application/pdf") {
      setError("Only PDF documents are allowed.");
      return;
    }

    if (file.size > 10 * 1024 * 1024) {
      setError("Document file size must not exceed 10 MB.");
      return;
    }

    setUploadedFile(file);
    setError("");
  }

  async function handleSubmit(status: SubmitStatus) {
    if (!name.trim()) {
      setError("Plenary name is required.");
      return;
    }

    if (!meetingDate) {
      setError("Meeting date is required.");
      return;
    }

    if (!meetingTime) {
      setError("Meeting time is required.");
      return;
    }

    if (!deadline) {
      setError("Deadline is required.");
      return;
    }

    if (!deadlineTime) {
      setError("Deadline time is required.");
      return;
    }

    if (status === "Sent" && selectedMinistryIds.length === 0) {
      setError("Please select at least one related Ministry.");
      return;
    }

    setSaving(true);
    setError("");

    try {
      const meetingDateTime = toIsoDateTime(meetingDate, meetingTime);

      const deadlineDateTime = toIsoDateTime(deadline, deadlineTime);

      const createdPlenary = await createPlenary({
        name: name.trim(),
        meetingDate: meetingDateTime,
        deadline: deadlineDateTime,
        status,
        ministryIds: selectedMinistryIds,
      });

      if (uploadedFile) {
        await uploadPlenaryDocument(createdPlenary.id, uploadedFile);
      }

      resetForm();
      onCreated();
      onClose();
    } catch (submitError: unknown) {
      setError(getErrorMessage(submitError));
    } finally {
      setSaving(false);
    }
  }

  const inputSx = {
    "& .MuiOutlinedInput-root": {
      height: 45,
      borderRadius: "11px",
      backgroundColor: theme.palette.background.paper,
      color: theme.palette.text.primary,
      "& fieldset": {
        borderColor: alpha(theme.palette.text.primary, 0.22),
      },
      "&:hover fieldset": {
        borderColor: alpha(theme.palette.text.primary, 0.36),
      },
      "&.Mui-focused fieldset": {
        borderColor: theme.palette.primary.main,
      },
    },
    "& .MuiInputBase-input": {
      fontSize: 16,
    },
  };

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth={false}
      slotProps={{
        paper: {
          sx: {
            width: 880,
            maxWidth: "calc(100vw - 32px)",
            height: { xs: "auto", md: 660 },
            minHeight: { xs: 0, md: 660 },
            maxHeight: "88vh",
            borderRadius: "20px",
            overflow: "hidden",
            bgcolor: theme.palette.background.paper,
            color: theme.palette.text.primary,
          },
        },
        backdrop: {
          sx: {
            bgcolor: "rgba(0, 0, 0, 0.55)",
          },
        },
      }}
    >
      <Box
        sx={{
          overflowY: "auto",
          p: { xs: 2, md: "22px 34px 20px" },
        }}
      >
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            gap: 2,
            mb: 2.25,
          }}
        >
          <Typography
            sx={{
              fontSize: { xs: 26, md: 31 },
              fontWeight: 800,
              color: theme.palette.text.primary,
            }}
          >
            Create Plenary
          </Typography>

          <Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
            <Button
              variant="contained"
              disabled={saving}
              onClick={() => handleSubmit("Draft")}
              sx={{
                height: 45,
                px: { xs: 2, md: 3.5 },
                borderRadius: "10px",
                bgcolor: "#B9B9B9",
                color: "#FFFFFF",
                fontWeight: 800,
                fontSize: 16,
                textTransform: "none",
                boxShadow: "none",
                "&:hover": {
                  bgcolor: "#A6A6A6",
                  boxShadow: "none",
                },
              }}
            >
              {saving ? "Saving..." : "↔ Save Draft"}
            </Button>

            <Button
              variant="contained"
              disabled={saving || loadingMinistries}
              onClick={() => handleSubmit("Sent")}
              sx={{
                height: 45,
                px: { xs: 2, md: 3.8 },
                borderRadius: "10px",
                bgcolor: theme.palette.primary.main,
                color: "#FFFFFF",
                fontWeight: 800,
                fontSize: 16,
                textTransform: "none",
                boxShadow: "none",
                "&:hover": {
                  bgcolor: theme.palette.primary.dark,
                  boxShadow: "none",
                },
              }}
            >
              ✓ Send Notification
            </Button>
          </Box>
        </Box>

        {error ? (
          <Alert severity="error" onClose={() => setError("")} sx={{ mb: 2 }}>
            {error}
          </Alert>
        ) : null}

        <Typography sx={{ mb: 1, fontSize: 16, fontWeight: 600 }}>
          Name
        </Typography>

        <TextField
          fullWidth
          value={name}
          placeholder="Input plenary name"
          onChange={(event) => setName(event.target.value)}
          sx={{ mb: 2.25, ...inputSx }}
          slotProps={{
            input: {
              startAdornment: (
                <InputAdornment position="start">
                  <PersonOutlineOutlinedIcon
                    sx={{
                      fontSize: 19,
                      color: theme.palette.text.secondary,
                    }}
                  />
                </InputAdornment>
              ),
            },
          }}
        />

        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
            gap: { xs: 2, md: 4 },
          }}
        >
          <Box>
            <Typography sx={{ mb: 1, fontSize: 16, fontWeight: 600 }}>
              Meeting Date{" "}
              <Box component="span" sx={{ color: "#F04438" }}>
                *
              </Box>
            </Typography>

            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: {
                  xs: "1fr",
                  sm: "minmax(0, 1fr) 175px",
                },
                gap: 1.25,
              }}
            >
              <TextField
                fullWidth
                type="date"
                value={meetingDate}
                onChange={(event) => setMeetingDate(event.target.value)}
                sx={inputSx}
              />

              <TimeSelectField value={meetingTime} onChange={setMeetingTime} />
            </Box>
          </Box>

          <Box>
            <Typography sx={{ mb: 1, fontSize: 16, fontWeight: 600 }}>
              Deadline{" "}
              <Box component="span" sx={{ color: "#F04438" }}>
                *
              </Box>
            </Typography>

            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: {
                  xs: "1fr",
                  sm: "minmax(0, 1fr) 175px",
                },
                gap: 1.25,
              }}
            >
              <TextField
                fullWidth
                type="date"
                value={deadline}
                onChange={(event) => setDeadline(event.target.value)}
                sx={inputSx}
              />

              <TimeSelectField
                value={deadlineTime}
                onChange={setDeadlineTime}
              />
            </Box>
          </Box>
        </Box>

        <Box
          sx={{
            mt: 2,
            display: "grid",
            gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
            gap: { xs: 2.25, md: 4 },
            alignItems: "start",
          }}
        >
          <Box>
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
                gap: 1.25,
                mb: 1.25,
              }}
            >
              <AttachFileOutlinedIcon
                sx={{ color: theme.palette.text.secondary }}
              />

              <Typography
                sx={{
                  color: theme.palette.text.secondary,
                  fontSize: 16,
                }}
              >
                Document Reference:
              </Typography>
            </Box>

            {uploadedFile ? (
              <Box
                sx={{
                  minHeight: 140,
                  display: "flex",
                  alignItems: "center",
                  gap: 2,
                  px: 2,
                }}
              >
                <Box
                  sx={{
                    width: 52,
                    height: 60,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    borderRadius: "8px",
                    border: `2px solid ${alpha(
                      theme.palette.text.primary,
                      0.2,
                    )}`,
                    color: "#EF4444",
                  }}
                >
                  <FilePresentOutlinedIcon />
                </Box>

                <Box>
                  <Typography
                    sx={{
                      fontWeight: 700,
                      fontSize: 16,
                      wordBreak: "break-word",
                    }}
                  >
                    {uploadedFile.name}
                  </Typography>

                  <Typography
                    sx={{
                      mt: 0.5,
                      color: theme.palette.text.secondary,
                      fontSize: 15,
                    }}
                  >
                    {Math.ceil(uploadedFile.size / 1024)} KB
                  </Typography>
                </Box>
              </Box>
            ) : (
              <Box
                component="label"
                sx={{
                  minHeight: 150,
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  justifyContent: "center",
                  cursor: "pointer",
                  borderRadius: "14px",
                }}
              >
                <input
                  hidden
                  type="file"
                  accept="application/pdf,.pdf"
                  onChange={handleFileChange}
                />

                <CloudUploadOutlinedIcon
                  sx={{
                    mb: 0.75,
                    fontSize: 46,
                    color: theme.palette.primary.main,
                  }}
                />

                <Typography sx={{ fontSize: 16 }}>
                  <Box
                    component="span"
                    sx={{
                      color: theme.palette.primary.main,
                      fontWeight: 800,
                    }}
                  >
                    Click to upload
                  </Box>{" "}
                  or drag and drop
                </Typography>

                <Typography
                  sx={{
                    mt: 0.25,
                    fontSize: 14,
                    color: theme.palette.text.secondary,
                  }}
                >
                  PDF 10MB
                </Typography>
              </Box>
            )}
          </Box>

          <Box>
            <Box
              onClick={() => setOpenMinistry((previous) => !previous)}
              sx={{
                display: "flex",
                alignItems: "center",
                gap: 1.5,
                mb: 1,
                cursor: "pointer",
                width: "fit-content",
              }}
            >
              <Typography sx={{ fontSize: 16, fontWeight: 700 }}>
                Select Related Ministry
              </Typography>

              {openMinistry ? (
                <ExpandLessOutlinedIcon fontSize="small" />
              ) : (
                <ExpandMoreOutlinedIcon fontSize="small" />
              )}
            </Box>

            {openMinistry ? (
              <Box sx={{ height: 205, overflowY: "auto", pr: 0.75 }}>
                {loadingMinistries ? (
                  <Box
                    sx={{
                      height: 150,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                    }}
                  >
                    <CircularProgress size={30} />
                  </Box>
                ) : null}

                {!loadingMinistries && ministries.length === 0 ? (
                  <Box
                    sx={{
                      height: 150,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                    }}
                  >
                    <Typography color="text.secondary">
                      No related Ministries found.
                    </Typography>
                  </Box>
                ) : null}

                {!loadingMinistries
                  ? ministries.map((ministry) => {
                      const isSelected = selectedMinistryIds.includes(
                        ministry.id,
                      );

                      return (
                        <Box
                          key={ministry.id}
                          onClick={() => toggleMinistry(ministry.id)}
                          sx={{
                            minHeight: 56,
                            px: 1,
                            display: "flex",
                            alignItems: "center",
                            gap: 1.4,
                            borderRadius: "9px",
                            cursor: "pointer",
                            bgcolor: isSelected
                              ? alpha(theme.palette.primary.main, 0.08)
                              : "transparent",
                            "&:hover": {
                              bgcolor: alpha(theme.palette.primary.main, 0.1),
                            },
                          }}
                        >
                          <Checkbox
                            checked={isSelected}
                            onClick={(event) => event.stopPropagation()}
                            onChange={() => toggleMinistry(ministry.id)}
                            sx={{
                              p: 0.4,
                              color: alpha(theme.palette.text.primary, 0.35),
                              "&.Mui-checked": {
                                color: theme.palette.primary.main,
                              },
                            }}
                          />

                          <Avatar
                            src={getMinistryLogoUrl(ministry.logo)}
                            alt={ministry.name}
                            sx={{
                              width: 36,
                              height: 36,
                              bgcolor: alpha(theme.palette.primary.main, 0.14),
                              color: theme.palette.primary.main,
                              fontSize: 14,
                              fontWeight: 800,
                              border: `1px solid ${alpha(
                                theme.palette.primary.main,
                                0.18,
                              )}`,
                            }}
                          >
                            {ministry.name.charAt(0).toUpperCase()}
                          </Avatar>

                          <Typography
                            sx={{
                              fontSize: 16,
                              fontWeight: 700,
                            }}
                          >
                            {ministry.name}
                          </Typography>
                        </Box>
                      );
                    })
                  : null}
              </Box>
            ) : null}
          </Box>
        </Box>
      </Box>
    </Dialog>
  );
}
