"use client";

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

import AddBoxOutlinedIcon from "@mui/icons-material/AddBoxOutlined";
import CalendarMonthOutlinedIcon from "@mui/icons-material/CalendarMonthOutlined";
import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
import CloudDownloadOutlinedIcon from "@mui/icons-material/CloudDownloadOutlined";
import CloudUploadOutlinedIcon from "@mui/icons-material/CloudUploadOutlined";
import LocationOnOutlinedIcon from "@mui/icons-material/LocationOnOutlined";
import ReplayRoundedIcon from "@mui/icons-material/ReplayRounded";
import Alert from "@mui/material/Alert";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { enUS } from "date-fns/locale/en-US";

import { AppTextEditor } from "@/components/ui/text-editor";
import { AlertDialog } from "@/components/ui/alert-dialog";
import { PrintButton } from "@/components/ui/print-button";
import type {
  MeetingRequest,
  MeetingRequestGovernmentAgency,
  MeetingRequestIssue,
} from "@/features/ministry/meeting-request/meeting-request-data";
import { MeetingPrintView } from "@/features/ministry/meeting-request/components/print/meeting-print-view";
import {
  dateToMeetingFormValue,
  emptyMeetingCreateForm,
  formatMeetingDate,
  formatMeetingTimeRange,
  meetingFormValueToDate,
  validateMeetingForm,
  type MeetingCreateForm,
  type MeetingCreateFormErrors,
} from "../../meeting-create-form";
import { MeetingCreateIssuesSection } from "../meeting-create-issues-section";
import { MeetingGuestPicker, type GuestEntry } from "../meeting-guest-picker";
import { MeetingTimePicker } from "../meeting-time-picker";
import { LinkMeetingRequestPopover } from "./link-meeting-request-popover";
import {
  AddIssuePopup,
  mapAddIssueFormToMeetingRequestIssue,
  type AddMeetingIssueFormValues,
} from "./add-issue-popup";

const DRAFT_STORAGE_KEY = "ministry-meeting-draft";
const PICKER_Z_INDEX = 1700;

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

type MeetingCreateDialogProps = {
  open: boolean;
  onClose: () => void;
  onSchedule?: (form: MeetingCreateForm) => Promise<void> | void;
  onSaveDraft?: (form: MeetingCreateForm) => Promise<void> | void;
  onSaveChange?: (form: MeetingCreateForm) => Promise<void> | void;
  isEditing?: boolean;
  initialForm?: Partial<MeetingCreateForm>;
  showIssueActions?: boolean;
  confirmBeforeSchedule?: boolean;
  title?: string;
  issues?: MeetingRequestIssue[];
  governmentAgencies?: MeetingRequestGovernmentAgency[];
  meetingRequest?: Pick<
    MeetingRequest,
    | "id"
    | "requestedBy"
    | "requestedDate"
    | "documentName"
    | "privateSectorWG"
    | "submittedBy"
  > & { status?: string };
};

type MeetingCreateDialogContentProps = Omit<MeetingCreateDialogProps, "open">;

type LinkedMeetingRequestData = {
  issues: MeetingRequestIssue[];
  governmentAgencies?: MeetingRequestGovernmentAgency[];
  meetingRequest: NonNullable<MeetingCreateDialogProps["meetingRequest"]>;
  linkedRequestIds: number[];
};

function mergeLinkedMeetingRequests(
  requests: MeetingRequest[],
): LinkedMeetingRequestData | null {
  if (requests.length === 0) return null;

  const agencyMap = new Map<number, MeetingRequestGovernmentAgency>();

  requests.forEach((request) => {
    request.governmentAgencies?.forEach((agency) => {
      agencyMap.set(agency.id, agency);
    });
  });

  const primary = requests[0];

  return {
    issues: requests.flatMap((request) => request.issues),
    governmentAgencies: Array.from(agencyMap.values()),
    meetingRequest: {
      id: primary.id,
      requestedBy: primary.requestedBy,
      requestedDate: primary.requestedDate,
      documentName: primary.documentName,
      privateSectorWG: primary.privateSectorWG,
      submittedBy: primary.submittedBy,
    },
    linkedRequestIds: requests.map((request) => request.id),
  };
}

function getInitialForm(): MeetingCreateForm {
  return { ...emptyMeetingCreateForm };
}

function normalizeForm(form: Partial<MeetingCreateForm>): MeetingCreateForm {
  return {
    ...emptyMeetingCreateForm,
    ...form,
    guestEntries: form.guestEntries ?? [],
  };
}

function resolveInitialForm(
  seed?: Partial<MeetingCreateForm>,
): MeetingCreateForm {
  if (seed) {
    return normalizeForm(seed);
  }

  return getInitialFormState();
}

function getInitialFormState(): MeetingCreateForm {
  if (typeof window !== "undefined") {
    const savedDraft = localStorage.getItem(DRAFT_STORAGE_KEY);

    if (savedDraft) {
      try {
        return normalizeForm(
          JSON.parse(savedDraft) as Partial<MeetingCreateForm>,
        );
      } catch {
        localStorage.removeItem(DRAFT_STORAGE_KEY);
      }
    }
  }

  return getInitialForm();
}

function buildMeetingPrintRequest(
  form: MeetingCreateForm,
  options: {
    meetingRequest?: MeetingCreateDialogProps["meetingRequest"];
    governmentAgencies?: MeetingRequestGovernmentAgency[];
    issues?: MeetingRequestIssue[];
  },
): MeetingRequest {
  const { meetingRequest, governmentAgencies, issues } = options;
  const issueList = issues ?? [];

  return {
    id: meetingRequest?.id ?? 0,
    title: form.title.trim() || "Untitled Meeting",
    description: form.description,
    status: "Draft",
    canCreateMeeting: false,
    issueCount: issueList.length,
    documentName: form.document?.name ?? meetingRequest?.documentName ?? "",
    requestedDate: meetingRequest?.requestedDate ?? "-",
    requestedBy: meetingRequest?.requestedBy ?? "-",
    year: new Date().getFullYear(),
    privateSectorWG: meetingRequest?.privateSectorWG,
    submittedBy: meetingRequest?.submittedBy,
    governmentAgencies,
    issues: issueList,
  };
}

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

  return (
    <Typography
      sx={{
        mb: 0.75,
        fontSize: 12,
        fontWeight: 500,
        color: theme.palette.text.primary,
      }}
    >
      {children}
      {required ? (
        <Box component="span" sx={{ color: "#f04438" }}>
          {" "}
          *
        </Box>
      ) : null}
    </Typography>
  );
}

function MeetingCreateDialogContent({
  onClose,
  onSchedule,
  onSaveDraft,
  onSaveChange,
  isEditing = false,
  initialForm,
  showIssueActions = true,
  confirmBeforeSchedule = false,
  title = "Create Meeting",
  issues,
  governmentAgencies,
  meetingRequest,
}: MeetingCreateDialogContentProps) {
  const theme = useTheme();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [form, setForm] = useState<MeetingCreateForm>(() =>
    resolveInitialForm(initialForm),
  );
  const [errors, setErrors] = useState<MeetingCreateFormErrors>({});
  const [message, setMessage] = useState("");
  const [messageType, setMessageType] = useState<"success" | "error">(
    "success",
  );
  const [isSavingDraft, setIsSavingDraft] = useState(false);
  const [isScheduling, setIsScheduling] = useState(false);
  const [isSavingChange, setIsSavingChange] = useState(false);
  const [scheduleConfirmOpen, setScheduleConfirmOpen] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [linkMeetingRequestOpen, setLinkMeetingRequestOpen] = useState(false);
  const [addIssueOpen, setAddIssueOpen] = useState(false);
  const [linkedMeetingRequestData, setLinkedMeetingRequestData] =
    useState<LinkedMeetingRequestData | null>(null);
  const [manualIssues, setManualIssues] = useState<MeetingRequestIssue[]>([]);

  const isDark = theme.palette.mode === "dark";
  const borderColor = isDark
    ? alpha(theme.palette.common.white, 0.14)
    : "#e5e7eb";
  const softBackground = isDark
    ? alpha(theme.palette.common.white, 0.04)
    : "#fafafa";

  const resolvedIssues = useMemo(() => {
    const merged = [
      ...(issues ?? []),
      ...(linkedMeetingRequestData?.issues ?? []),
      ...manualIssues,
    ];

    const seen = new Set<number>();

    return merged.filter((item) => {
      if (seen.has(item.id)) return false;
      seen.add(item.id);
      return true;
    });
  }, [issues, linkedMeetingRequestData, manualIssues]);
  const resolvedGovernmentAgencies =
    governmentAgencies ?? linkedMeetingRequestData?.governmentAgencies;
  const resolvedMeetingRequest =
    meetingRequest ?? linkedMeetingRequestData?.meetingRequest;
  const hasIssues = resolvedIssues.length > 0;

  const printMeetingRequest = useMemo(
    () =>
      buildMeetingPrintRequest(form, {
        meetingRequest: resolvedMeetingRequest,
        governmentAgencies: resolvedGovernmentAgencies,
        issues: resolvedIssues,
      }),
    [form, resolvedMeetingRequest, resolvedGovernmentAgencies, resolvedIssues],
  );

  const handlePrint = () => {
    window.print();
  };

  const handleOpenLinkMeetingRequest = () => {
    setLinkMeetingRequestOpen(true);
  };

  const handleCloseLinkMeetingRequest = () => {
    setLinkMeetingRequestOpen(false);
  };

  const handleOpenAddIssue = () => {
    setAddIssueOpen(true);
  };

  const handleCloseAddIssue = () => {
    setAddIssueOpen(false);
  };

  const handleSaveAddIssue = (values: AddMeetingIssueFormValues) => {
    setManualIssues((current) => [
      ...current,
      mapAddIssueFormToMeetingRequestIssue(values, Date.now() + current.length),
    ]);
    setAddIssueOpen(false);
  };

  const handleConfirmLinkedMeetingRequests = (requests: MeetingRequest[]) => {
    const linkedData = mergeLinkedMeetingRequests(requests);
    const primary = requests[0];

    if (!linkedData || !primary) return;

    setLinkedMeetingRequestData(linkedData);
    setForm((current) => ({
      ...current,
      meetingRequestId: linkedData.meetingRequest.id,
      title: current.title.trim() || primary.title,
      description: current.description.trim() || primary.description,
      document:
        current.document ??
        (primary.documentName
          ? {
              name: primary.documentName,
              type: "application/pdf",
              size: 0,
            }
          : null),
    }));
  };

  const updateForm = <Key extends keyof MeetingCreateForm>(
    key: Key,
    value: MeetingCreateForm[Key],
  ) => {
    setForm((current) => ({ ...current, [key]: value }));
    setErrors((current) => ({ ...current, [key]: undefined }));
  };

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

    if (!file) return;

    setUploadProgress(0);
    updateForm("document", {
      name: file.name,
      type: file.type,
      size: file.size,
    });
  };

  useEffect(() => {
    if (!form.document) return;

    const step = 100 / 15;
    let current = 0;
    const id = setInterval(() => {
      current = Math.min(100, current + step);
      setUploadProgress(Math.round(current));
      if (current >= 100) clearInterval(id);
    }, 80);

    return () => clearInterval(id);
  }, [form.document]);

  const getErrorMessage = (error: unknown) => {
    return error instanceof Error ? error.message : "Unable to save meeting.";
  };

  const handleSaveDraft = async () => {
    setMessage("");
    setMessageType("success");
    setIsSavingDraft(true);

    try {
      if (onSaveDraft) {
        await onSaveDraft(form);
        localStorage.removeItem(DRAFT_STORAGE_KEY);
        setForm(getInitialForm());
        onClose();
        return;
      }

      localStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(form));
      setMessage("Draft saved on this device.");
    } catch (error) {
      setMessageType("error");
      setMessage(getErrorMessage(error));
    } finally {
      setIsSavingDraft(false);
    }
  };

  const scheduleMeeting = async () => {
    setScheduleConfirmOpen(false);
    setMessage("");
    setMessageType("success");
    setIsScheduling(true);

    try {
      await onSchedule?.(form);
      localStorage.removeItem(DRAFT_STORAGE_KEY);
      setForm(getInitialForm());
      onClose();
    } catch (error) {
      setMessageType("error");
      setMessage(getErrorMessage(error));
    } finally {
      setIsScheduling(false);
    }
  };

  const handleSchedule = () => {
    const nextErrors = validateMeetingForm(form);

    setErrors(nextErrors);

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

    if (confirmBeforeSchedule) {
      setScheduleConfirmOpen(true);
      return;
    }

    void scheduleMeeting();
  };

  // Save Change keeps the current meeting status.
  const handleSaveChange = async () => {
    if (normalizedStatus !== "DRAFT" && normalizedStatus !== "DRAFTED") {
      const nextErrors = validateMeetingForm(form);

      setErrors(nextErrors);

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

    setMessage("");
    setMessageType("success");
    setIsSavingChange(true);

    try {
      await onSaveChange?.(form);
      localStorage.removeItem(DRAFT_STORAGE_KEY);
      setForm(getInitialForm());
      onClose();
    } catch (error) {
      setMessageType("error");
      setMessage(getErrorMessage(error));
    } finally {
      setIsSavingChange(false);
    }
  };

  // Meeting statuses arrive from the backend in uppercase enum format.
  const normalizedStatus = (form.status ?? "").trim().toUpperCase();
  const isDraftEdit =
    isEditing &&
    (normalizedStatus === "DRAFT" || normalizedStatus === "DRAFTED");
  const showSaveChangeOnly = isEditing && !isDraftEdit && Boolean(onSaveChange);

  const inputSx = {
    "& .MuiOutlinedInput-root": {
      height: 40,
      borderRadius: "6px",
      bgcolor: softBackground,
      fontSize: 12,
    },
    "& .MuiOutlinedInput-notchedOutline": {
      borderColor,
    },
    "& .MuiInputBase-input": {
      fontSize: 12,
    },
  };

  return (
    <>
      <Dialog
        open
        onClose={onClose}
        maxWidth={false}
        scroll="paper"
        sx={{
          zIndex: 1600,
          "& .MuiBackdrop-root": {
            bgcolor: "rgba(0, 0, 0, 0.5)",
          },
        }}
        slotProps={{
          paper: {
            sx: {
              width: { xs: "calc(100vw - 24px)", md: 795 },
              maxWidth: "calc(100vw - 24px)",
              maxHeight: "calc(100dvh - 34px)",
              m: 0,
              borderRadius: "12px",
              bgcolor: theme.palette.background.paper,
              backgroundImage: "none",
              overflow: "hidden",
            },
          },
        }}
      >
        <Box
          sx={{
            minHeight: 74,
            px: 2.75,
            py: 1.5,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            gap: 2,
            borderBottom: `1px solid ${borderColor}`,
          }}
        >
          <Typography sx={{ fontSize: 20, fontWeight: 500 }}>
            {title}
          </Typography>

          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              justifyContent: "flex-end",
              flexWrap: "wrap",
              gap: 1.5,
            }}
          >
            <PrintButton onClick={handlePrint} />

            {showSaveChangeOnly ? (
              // Already Submitted / Completed: one button that saves the
              // edits without touching the meeting's status.
              <Button
                variant="contained"
                startIcon={<CheckRoundedIcon sx={{ fontSize: 24 }} />}
                onClick={handleSaveChange}
                disabled={isSavingChange}
                sx={{
                  minHeight: 44,
                  px: 1.5,
                  py: 1.25,
                  gap: 1.25,
                  borderRadius: "6px",
                  bgcolor: "#1a64a8",
                  color: "#ffffff",
                  boxShadow: "none",
                  textTransform: "none",
                  fontSize: 13,
                  fontWeight: 500,
                  lineHeight: 1,
                  "& .MuiButton-startIcon": {
                    m: 0,
                  },
                  "&:hover": { bgcolor: "#155489", boxShadow: "none" },
                  "&.Mui-disabled": {
                    bgcolor: "#8ab7df",
                    color: "#ffffff",
                  },
                }}
              >
                {isSavingChange ? "Saving..." : "Save Change"}
              </Button>
            ) : (
              <>
                <Button
                  variant="contained"
                  startIcon={
                    isDraftEdit ? (
                      <CheckRoundedIcon sx={{ fontSize: 24 }} />
                    ) : (
                      <ReplayRoundedIcon sx={{ fontSize: 24 }} />
                    )
                  }
                  onClick={isDraftEdit ? handleSaveChange : handleSaveDraft}
                  disabled={
                    isDraftEdit
                      ? isSavingChange || isScheduling
                      : isSavingDraft || isScheduling
                  }
                  sx={{
                    minHeight: 44,
                    px: 1.5,
                    py: 1.25,
                    gap: 1.25,
                    borderRadius: "6px",
                    bgcolor: isDraftEdit ? "#1a64a8" : "#bdbdbd",
                    color: "#ffffff",
                    boxShadow: "none",
                    textTransform: "none",
                    fontSize: 13,
                    fontWeight: 500,
                    lineHeight: 1,
                    "& .MuiButton-startIcon": {
                      m: 0,
                    },
                    "&:hover": {
                      bgcolor: isDraftEdit ? "#155489" : "#a8a8a8",
                      boxShadow: "none",
                    },
                    "&.Mui-disabled": {
                      bgcolor: isDraftEdit ? "#8ab7df" : "#c8c8c8",
                      color: "#ffffff",
                    },
                  }}
                >
                  {isDraftEdit
                    ? isSavingChange
                      ? "Saving..."
                      : "Save Change"
                    : isSavingDraft
                      ? "Saving..."
                      : "Save Draft"}
                </Button>

                <Button
                  variant="contained"
                  startIcon={<CheckRoundedIcon sx={{ fontSize: 24 }} />}
                  onClick={handleSchedule}
                  disabled={isSavingDraft || isSavingChange || isScheduling}
                  sx={{
                    minWidth: 223,
                    minHeight: 44,
                    px: 1.5,
                    py: 1.25,
                    gap: 1.25,
                    borderRadius: "6px",
                    bgcolor: "#1a64a8",
                    color: "#ffffff",
                    boxShadow: "none",
                    textTransform: "none",
                    fontSize: 13,
                    fontWeight: 500,
                    lineHeight: 1,
                    "& .MuiButton-startIcon": {
                      m: 0,
                    },
                    "&:hover": { bgcolor: "#155489", boxShadow: "none" },
                    "&.Mui-disabled": {
                      bgcolor: "#8ab7df",
                      color: "#ffffff",
                    },
                  }}
                >
                  {isScheduling ? "Scheduling..." : "Schedule and Send Invites"}
                </Button>
              </>
            )}
          </Box>
        </Box>

        <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={enUS}>
          <Box
            sx={{
              px: 2.75,
              py: 1.5,
              overflowY: "auto",
            }}
          >
            {message ? (
              <Alert severity={messageType} sx={{ mb: 1.5 }}>
                {message}
              </Alert>
            ) : null}

            <FieldLabel required>Title Meeting</FieldLabel>
            <TextField
              fullWidth
              value={form.title}
              onChange={(event) => updateForm("title", event.target.value)}
              placeholder="Write a meeting title"
              error={Boolean(errors.title)}
              helperText={errors.title}
              sx={inputSx}
            />

            <Box sx={{ mt: 1 }}>
              <FieldLabel>Description</FieldLabel>
              <AppTextEditor
                minRows={4}
                value={form.description}
                onChange={(value) => updateForm("description", value)}
                placeholder="Write a description............"
              />
            </Box>

            <Box
              sx={{
                mt: 1.25,
                display: "grid",
                gridTemplateColumns: {
                  xs: "minmax(0, 1fr)",
                  md: "repeat(3, minmax(0, 1fr))",
                },
                gap: 1.5,
              }}
            >
              <Box sx={{ minWidth: 0 }}>
                <FieldLabel required>Date</FieldLabel>
                <DatePicker
                  value={meetingFormValueToDate(form.date)}
                  onChange={(date) =>
                    updateForm("date", dateToMeetingFormValue(date))
                  }
                  format="MMMM d, yyyy"
                  slotProps={{
                    actionBar: {
                      actions: ["today"],
                      sx: {
                        minHeight: 48,
                        px: 2,
                        py: 0.5,
                        justifyContent: "flex-start",
                        borderTop: `1px solid ${borderColor}`,
                        "& .MuiButton-root": {
                          minWidth: 54,
                          minHeight: 32,
                          px: 1.5,
                          border: `1px solid ${borderColor}`,
                          borderRadius: "6px",
                          color: "text.primary",
                          fontSize: 11,
                          fontWeight: 500,
                          textTransform: "none",
                        },
                      },
                    },
                    field: {
                      clearable: true,
                    },
                    popper: {
                      sx: { zIndex: PICKER_Z_INDEX },
                    },
                    textField: {
                      fullWidth: true,
                      error: Boolean(errors.date),
                      helperText: errors.date,
                      sx: {
                        ...inputSx,
                        width: "100%",
                        minWidth: 0,
                        "& .MuiPickersOutlinedInput-root, & .MuiOutlinedInput-root":
                          {
                            width: "100%",
                            height: 40,
                            minHeight: 40,
                            minWidth: 0,
                            borderRadius: "6px",
                            bgcolor: softBackground,
                            fontSize: 12,
                            py: 0,
                          },
                        "& .MuiPickersOutlinedInput-notchedOutline, & .MuiOutlinedInput-notchedOutline":
                          {
                            borderColor,
                          },
                        "& .MuiPickersInputBase-input, & .MuiInputBase-input": {
                          minWidth: 0,
                          overflow: "hidden",
                          fontSize: 12,
                          fontWeight: 400,
                          lineHeight: 1.24,
                          textOverflow: "ellipsis",
                          py: 0,
                        },
                        "& .MuiPickersSectionList-root": {
                          py: 0,
                        },
                      },
                    },
                    openPickerButton: {
                      sx: {
                        mr: -0.5,
                        color: "text.secondary",
                        "& .MuiSvgIcon-root": { fontSize: 20 },
                      },
                    },
                    desktopPaper: {
                      sx: {
                        width: 280,
                        mt: 0.75,
                        border: `1px solid ${borderColor}`,
                        borderRadius: "11px",
                        boxShadow: "0 4px 16px rgba(16, 24, 40, 0.14)",
                        overflow: "hidden",
                        "& .MuiPickersLayout-root": {
                          minWidth: 280,
                        },
                        "& .MuiDateCalendar-root": {
                          width: 280,
                          maxHeight: 322,
                        },
                        "& .MuiPickersCalendarHeader-root": {
                          minHeight: 40,
                          mt: 1,
                          mb: 0.5,
                          px: 1.25,
                        },
                        "& .MuiPickersCalendarHeader-label": {
                          fontSize: 12,
                          fontWeight: 500,
                        },
                        "& .MuiPickersArrowSwitcher-button": {
                          width: 32,
                          height: 32,
                        },
                        "& .MuiDayCalendar-weekDayLabel": {
                          width: 36,
                          height: 30,
                          m: "0 2px",
                          color: "text.secondary",
                          fontSize: 11,
                          fontWeight: 500,
                        },
                        "& .MuiDayCalendar-weekContainer": {
                          my: 0,
                        },
                        "& .MuiPickerDay-root": {
                          position: "relative",
                          width: 36,
                          height: 36,
                          m: "0 2px",
                          borderRadius: "8px",
                          fontSize: 11,
                        },
                        "& .MuiPickerDay-root.Mui-selected": {
                          bgcolor: "#f2f4f7",
                          color: "#101828",
                        },
                        "& .MuiPickerDay-root.Mui-selected:hover, & .MuiPickerDay-root.Mui-selected:focus":
                          {
                            bgcolor: "#e9ecf1",
                          },
                        "& .MuiPickerDay-root.Mui-selected::after": {
                          position: "absolute",
                          bottom: 4,
                          left: "50%",
                          width: 4,
                          height: 4,
                          borderRadius: "50%",
                          bgcolor: "#9747ff",
                          content: '""',
                          transform: "translateX(-50%)",
                        },
                      },
                    },
                  }}
                  slots={{
                    openPickerIcon: CalendarMonthOutlinedIcon,
                  }}
                />
              </Box>

              <Box>
                <FieldLabel required>Start Time</FieldLabel>
                <MeetingTimePicker
                  value={form.startTime}
                  onChange={(value) => updateForm("startTime", value)}
                  error={Boolean(errors.startTime)}
                  helperText={errors.startTime}
                  inputSx={inputSx}
                />
              </Box>

              <Box>
                <FieldLabel required>End Time</FieldLabel>
                <MeetingTimePicker
                  value={form.endTime}
                  onChange={(value) => updateForm("endTime", value)}
                  error={Boolean(errors.endTime)}
                  helperText={errors.endTime}
                  inputSx={inputSx}
                />
              </Box>
            </Box>

            <Box sx={{ mt: 1 }}>
              <FieldLabel required>Add location</FieldLabel>
              <TextField
                fullWidth
                value={form.location}
                onChange={(event) => updateForm("location", event.target.value)}
                placeholder="Enter location"
                error={Boolean(errors.location)}
                helperText={errors.location}
                slotProps={{
                  input: {
                    startAdornment: (
                      <LocationOnOutlinedIcon
                        sx={{ mr: 1, fontSize: 18, color: "text.secondary" }}
                      />
                    ),
                  },
                }}
                sx={inputSx}
              />
            </Box>

            <Box sx={{ mt: 1 }}>
              <FieldLabel required>Add guest</FieldLabel>
              <MeetingGuestPicker
                value={form.guestEntries}
                meetingRequestId={resolvedMeetingRequest?.id}
                governmentAgencies={resolvedGovernmentAgencies}
                onChange={(entries: GuestEntry[]) => {
                  updateForm("guestEntries", entries);
                  updateForm("guests", entries.map((g) => g.email).join(", "));
                }}
                error={Boolean(errors.guests)}
                helperText={errors.guests}
              />
            </Box>

            <Box sx={{ mt: 1 }}>
              <FieldLabel required>Document Reference</FieldLabel>

              {form.document ? (
                /* ── Post-upload state ── */
                <Box
                  sx={{ display: "flex", gap: "18px", alignItems: "stretch" }}
                >
                  {/* File card */}
                  <Box
                    sx={{
                      flex: 1,
                      minWidth: 0,
                      height: 62,
                      bgcolor: softBackground,
                      borderRadius: "6px",
                      overflow: "hidden",
                      display: "flex",
                      alignItems: "center",
                      px: 1.5,
                      gap: 1.5,
                      position: "relative",
                    }}
                  >
                    {/* PDF file icon */}
                    <Box
                      sx={{
                        position: "relative",
                        width: 40,
                        height: 40,
                        flexShrink: 0,
                      }}
                    >
                      {/* page background */}
                      <Box
                        sx={{
                          position: "absolute",
                          top: 0,
                          bottom: 0,
                          left: "17.5%",
                          right: "2.5%",
                          bgcolor: isDark ? "#374151" : "#e5e7eb",
                          borderRadius: "3px",
                        }}
                      />
                      {/* PDF badge */}
                      <Box
                        sx={{
                          position: "absolute",
                          bottom: "15%",
                          left: "2.5%",
                          right: "32.5%",
                          bgcolor: "#f04438",
                          borderRadius: "2px",
                          px: 0.375,
                          py: 0.25,
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                        }}
                      >
                        <Typography
                          sx={{
                            fontSize: 8,
                            fontWeight: 700,
                            color: "#fff",
                            lineHeight: 1,
                          }}
                        >
                          PDF
                        </Typography>
                      </Box>
                    </Box>

                    {/* Name + size */}
                    <Box sx={{ minWidth: 0, flex: 1 }}>
                      <Typography
                        noWrap
                        sx={{
                          fontSize: 12,
                          fontWeight: 500,
                          color: isDark ? "#e5e7eb" : "#252b37",
                          lineHeight: 1.3,
                        }}
                      >
                        {form.document.name}
                      </Typography>
                      <Typography
                        sx={{
                          fontSize: 12,
                          fontWeight: 400,
                          color: isDark ? "#9ca3af" : "#414651",
                          lineHeight: 1.24,
                          mt: 0.5,
                        }}
                      >
                        {formatFileSize(form.document.size)}
                      </Typography>
                    </Box>

                    {/* Upload progress */}
                    {uploadProgress < 100 && (
                      <Box
                        sx={{
                          display: "flex",
                          flexDirection: "column",
                          alignItems: "center",
                          gap: 1,
                          flexShrink: 0,
                          mr: 0.5,
                        }}
                      >
                        <Typography
                          sx={{
                            fontSize: 11,
                            fontWeight: 500,
                            color: "#868686",
                            lineHeight: "16px",
                          }}
                        >
                          Uploading
                        </Typography>
                        <Box
                          sx={{
                            width: 80,
                            height: 4,
                            bgcolor: isDark ? alpha("#fff", 0.12) : "#fff",
                            borderRadius: "16px",
                            overflow: "hidden",
                          }}
                        >
                          <Box
                            sx={{
                              height: "100%",
                              width: `${uploadProgress}%`,
                              bgcolor: "#22c55e",
                              borderRadius: "16px",
                              transition: "width 0.08s linear",
                            }}
                          />
                        </Box>
                      </Box>
                    )}
                  </Box>

                  {/* Re-upload button */}
                  <Box
                    component="button"
                    type="button"
                    aria-label="Replace document"
                    onClick={() => fileInputRef.current?.click()}
                    sx={{
                      width: 62,
                      height: 62,
                      flexShrink: 0,
                      bgcolor: softBackground,
                      border: `1px dashed ${borderColor}`,
                      borderRadius: "12px",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      cursor: "pointer",
                      "&:hover": {
                        borderColor: theme.palette.primary.main,
                        bgcolor: alpha(theme.palette.primary.main, 0.04),
                      },
                    }}
                  >
                    <CloudDownloadOutlinedIcon
                      sx={{ fontSize: 26, color: theme.palette.primary.main }}
                    />
                  </Box>
                </Box>
              ) : (
                /* ── Empty / drop-zone state ── */
                <Box
                  component="button"
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  sx={{
                    width: "100%",
                    minHeight: 78,
                    border: `1px dashed ${borderColor}`,
                    borderRadius: "12px",
                    bgcolor: softBackground,
                    color: theme.palette.text.primary,
                    cursor: "pointer",
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    justifyContent: "center",
                    "&:hover": {
                      borderColor: theme.palette.primary.main,
                      bgcolor: alpha(theme.palette.primary.main, 0.02),
                    },
                  }}
                >
                  <CloudUploadOutlinedIcon
                    sx={{ fontSize: 28, color: theme.palette.primary.main }}
                  />
                  <Typography sx={{ mt: 0.25, fontSize: 11 }}>
                    <Box
                      component="span"
                      sx={{
                        color: theme.palette.primary.main,
                        fontWeight: 600,
                      }}
                    >
                      Click to upload
                    </Box>{" "}
                    or drag and drop
                  </Typography>
                  <Typography sx={{ fontSize: 10, color: "text.secondary" }}>
                    PDF up to 10 MB
                  </Typography>
                </Box>
              )}

              <input
                ref={fileInputRef}
                hidden
                type="file"
                accept="application/pdf"
                onChange={handleDocumentChange}
              />
              {errors.document ? (
                <Typography sx={{ mt: 0.5, fontSize: 12, color: "error.main" }}>
                  {errors.document}
                </Typography>
              ) : null}
            </Box>

            {(hasIssues || showIssueActions) && (
              <Box sx={{ mt: 1.5 }}>
                <Typography sx={{ fontSize: 16, fontWeight: 700, mb: 1.5 }}>
                  List of Issues
                </Typography>

                {showIssueActions ? (
                  <Box
                    sx={{
                      display: "flex",
                      flexWrap: "wrap",
                      gap: 1,
                      mb: hasIssues ? 1.5 : 0,
                    }}
                  >
                    <Button
                      variant="outlined"
                      startIcon={<AddBoxOutlinedIcon sx={{ fontSize: 24 }} />}
                      onClick={handleOpenLinkMeetingRequest}
                      sx={{
                        minHeight: 40,
                        px: 1.5,
                        gap: 1.5,
                        borderColor: "#1a64a8",
                        borderRadius: "6px",
                        color: "#1a64a8",
                        textTransform: "none",
                        fontSize: 13,
                        fontWeight: 500,
                        lineHeight: 1,
                        "& .MuiButton-startIcon": {
                          m: 0,
                        },
                        "&:hover": {
                          borderColor: "#155489",
                          bgcolor: "rgba(26, 100, 168, 0.04)",
                        },
                      }}
                    >
                      Link Meeting Request
                    </Button>

                    <Button
                      variant="contained"
                      onClick={handleOpenAddIssue}
                      sx={{
                        minHeight: 40,
                        p: 1.5,
                        borderRadius: "6px",
                        bgcolor: "#1a64a8",
                        color: "#edf8fd",
                        boxShadow: "none",
                        textTransform: "none",
                        fontSize: 13,
                        fontWeight: 500,
                        lineHeight: 1,
                        "&:hover": {
                          bgcolor: "#155489",
                          boxShadow: "none",
                        },
                      }}
                    >
                      Add Issue
                    </Button>
                  </Box>
                ) : null}

                {hasIssues ? (
                  <MeetingCreateIssuesSection
                    issues={resolvedIssues}
                    governmentAgencies={resolvedGovernmentAgencies}
                    meetingRequest={resolvedMeetingRequest}
                  />
                ) : null}
              </Box>
            )}
          </Box>
        </LocalizationProvider>
      </Dialog>

      <AlertDialog
        open={scheduleConfirmOpen}
        title="Schedule and send invites?"
        description="This meeting will be scheduled and invitations will be sent to all guests."
        confirmLabel="Schedule and Send"
        loading={isScheduling}
        zIndex={1800}
        onConfirm={() => void scheduleMeeting()}
        onCancel={() => setScheduleConfirmOpen(false)}
      />

      <LinkMeetingRequestPopover
        open={linkMeetingRequestOpen}
        selectedIds={linkedMeetingRequestData?.linkedRequestIds ?? []}
        onClose={handleCloseLinkMeetingRequest}
        onConfirm={handleConfirmLinkedMeetingRequests}
      />

      <AddIssuePopup
        open={addIssueOpen}
        onClose={handleCloseAddIssue}
        onSave={handleSaveAddIssue}
      />

      <MeetingPrintView
        meetingRequest={printMeetingRequest}
        issues={resolvedIssues}
        printVariant="calendar"
        printStatus={form.status ?? meetingRequest?.status}
        meetingDate={formatMeetingDate(form.date)}
        meetingTime={formatMeetingTimeRange(form.startTime, form.endTime)}
        meetingLocation={form.location.trim() || undefined}
        documentSize={
          form.document && form.document.size > 0
            ? formatFileSize(form.document.size)
            : undefined
        }
      />
    </>
  );
}

export function MeetingCreateDialog({
  open,
  onClose,
  onSchedule,
  onSaveDraft,
  onSaveChange,
  isEditing = false,
  initialForm,
  showIssueActions = true,
  confirmBeforeSchedule = false,
  title = "Create Meeting",
  issues,
  governmentAgencies,
  meetingRequest,
}: MeetingCreateDialogProps) {
  if (!open) return null;

  return (
    <MeetingCreateDialogContent
      onClose={onClose}
      onSchedule={onSchedule}
      onSaveDraft={onSaveDraft}
      onSaveChange={onSaveChange}
      isEditing={isEditing}
      initialForm={initialForm}
      showIssueActions={showIssueActions}
      confirmBeforeSchedule={confirmBeforeSchedule}
      title={title}
      issues={issues}
      governmentAgencies={governmentAgencies}
      meetingRequest={meetingRequest}
    />
  );
}
