"use client";

import {
  useRef,
  useState,
  type ChangeEvent,
  type DragEvent,
  type ReactNode,
} from "react";

import Box from "@mui/material/Box";
import Alert from "@mui/material/Alert";
import Drawer from "@mui/material/Drawer";
import IconButton from "@mui/material/IconButton";
import MenuItem from "@mui/material/MenuItem";
import Select from "@mui/material/Select";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { alpha, useTheme, type Theme } from "@mui/material/styles";

import CloseIcon from "@mui/icons-material/Close";

import { AppButton } from "@/components/ui/button";
import { AppDatePicker } from "@/components/ui/date-picker";
import { DocumentLink } from "@/components/ui/document-link";
import { AdditionalAgencyFields } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/additional-agency-fields";
import {
  getElevatedSelectMenuProps,
  getInputSx,
  getSelectSx,
} from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/add-dashboard-issue-dialog-styles";
import type { UploadStatus } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/add-dashboard-issue-dialog-types";
import { AgencySelect } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/agency-select";
import { EditorBox } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/editor-box";
import {
  IssueReferenceFileCard,
  IssuesReferenceUploadField,
} from "@/features/ministry/meeting-summary/components/create-meeting-summary/issues-reference-upload-field";
import {
  IssueStatusSelect,
  getInitialIssueStatus,
} from "@/features/ministry/meeting-summary/components/create-meeting-summary/issue-status-select";
import { useIssueStatusOptions } from "@/features/ministry/meeting-summary/hook/use-issue-status-options";
import {
  formatFileSize,
  type UploadedFileMetadata,
} from "@/lib/document-file";
import { format, isValid, parse } from "date-fns";

import {
  agencyDisplayNameToSelectId,
  agencySelectIdToDisplayName,
  agencySelectIdToLogo,
  buildProgressReportIssueAgencies,
  getEditableFieldValue,
} from "./progress-report-issue-agencies";
import type { MinistryProgressReportIssueRow } from "./progress-report-issues-data";

const DRAWER_Z_INDEX = 1700;
const SELECT_MENU_Z_INDEX = DRAWER_Z_INDEX + 100;
const PICKER_Z_INDEX = DRAWER_Z_INDEX + 100;
const MAX_PDF_SIZE_BYTES = 10 * 1024 * 1024;

const PSWG_OPTIONS = ["PSWG-A", "PSWG-B", "PSWG-C"] as const;

export type UpdateProgressReportIssueSavePayload = {
  issue: MinistryProgressReportIssueRow;
  issueStatusId: number;
  indicators?: string;
  progressSolution?: string;
  implementationChallenges?: string;
  requests?: string;
  sourceOfVerification?: string;
  linkToVerificationSource?: string;
  nextStep?: string;
  dateOfIssueSolution?: string;
  attachment: File | null;
};

type IssueAttachmentDisplay = UploadedFileMetadata;

type Props = {
  open: boolean;
  issue: MinistryProgressReportIssueRow | null;
  onClose: () => void;
  onSave?: (payload: UpdateProgressReportIssueSavePayload) => void | Promise<void>;
  readOnly?: boolean;
  onAddComment?: () => void;
  issueAttachment?: IssueAttachmentDisplay | null;
};

function DialogFieldLabel({ children }: { children: ReactNode }) {
  return (
    <Typography
      sx={{
        fontSize: 13,
        fontWeight: 500,
        color: "#414651",
        mb: "14px",
        lineHeight: 1,
      }}
    >
      {children}
    </Typography>
  );
}

function getDialogInputSx(theme: Theme) {
  return {
    ...getInputSx(theme),
    "& .MuiOutlinedInput-root": {
      height: 50,
      borderRadius: "6px",
      bgcolor: theme.palette.background.paper,
      color: theme.palette.text.primary,
      fontSize: 12,
    },
    "& .MuiInputBase-input": {
      fontSize: 12,
      py: 0,
    },
  };
}

function getDialogSelectSx(theme: Theme) {
  return {
    ...getSelectSx(theme),
    height: 40,
    "& .MuiSelect-select": {
      height: 40,
      minHeight: "40px !important",
      py: 0,
      display: "flex",
      alignItems: "center",
    },
  };
}

function parseIssueSolutionDate(value: string): Date | null {
  const trimmed = getEditableFieldValue(value);
  if (!trimmed) return null;

  const formats = ["MMMM dd, yyyy", "MMMM d, yyyy", "dd MMMM yyyy"];
  for (const pattern of formats) {
    const parsed = parse(trimmed, pattern, new Date());
    if (isValid(parsed)) return parsed;
  }

  const fallback = new Date(trimmed);
  return isValid(fallback) ? fallback : null;
}

function formatIssueSolutionDate(date: Date | null): string {
  if (!date || !isValid(date)) return "No data";
  return format(date, "MMMM dd, yyyy");
}

function ReadOnlyAttachmentField({
  attachment,
}: {
  attachment: IssueAttachmentDisplay | null | undefined;
}) {
  return (
    <Box sx={{ maxWidth: 375 }}>
      <DialogFieldLabel>Attachment</DialogFieldLabel>
      {attachment?.name?.trim() ? (
        <DocumentLink file={attachment}>
          <IssueReferenceFileCard
            name={attachment.name}
            sizeLabel={formatFileSize(attachment.size)}
            uploadStatus="completed"
          />
        </DocumentLink>
      ) : (
        <Box
          sx={{
            height: 62,
            borderRadius: "6px",
            border: "1px solid #e9eaeb",
            bgcolor: "#fafafa",
          }}
        />
      )}
    </Box>
  );
}

function IssueEditorField({
  label,
  onChange,
  placeholder,
  readOnly,
  value,
}: {
  label: string;
  onChange: (value: string) => void;
  placeholder: string;
  readOnly: boolean;
  value: string;
}) {
  return (
    <Box>
      <DialogFieldLabel>{label}</DialogFieldLabel>
      <EditorBox
        placeholder={placeholder}
        value={value}
        onChange={onChange}
        readOnly={readOnly}
      />
    </Box>
  );
}

type DialogContentProps = {
  issue: MinistryProgressReportIssueRow;
  onClose: () => void;
  onSave?: (payload: UpdateProgressReportIssueSavePayload) => void | Promise<void>;
  readOnly?: boolean;
  onAddComment?: () => void;
  issueAttachment?: IssueAttachmentDisplay | null;
};

function UpdateProgressReportIssueDialogContent({
  issue,
  onClose,
  onSave,
  readOnly = false,
  onAddComment,
  issueAttachment,
}: DialogContentProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { data: issueStatusOptions = [] } = useIssueStatusOptions();

  const agencyOptions = buildProgressReportIssueAgencies(issue);
  const selectMenuProps = getElevatedSelectMenuProps(theme, SELECT_MENU_Z_INDEX);

  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [primaryAgency, setPrimaryAgency] = useState(() =>
    agencyDisplayNameToSelectId(issue.primaryAgency, agencyOptions),
  );
  const [pswg, setPswg] = useState(issue.pswg);
  const [status, setStatus] = useState(() => getInitialIssueStatus(issue.status));
  const [secondAgency, setSecondAgency] = useState(() =>
    agencyDisplayNameToSelectId(issue.secondAgency, agencyOptions),
  );
  const [thirdAgency, setThirdAgency] = useState(() =>
    agencyDisplayNameToSelectId(issue.thirdAgency, agencyOptions),
  );
  const [fourthAgency, setFourthAgency] = useState(() =>
    agencyDisplayNameToSelectId(issue.fourthAgency, agencyOptions),
  );
  const [fifthAgency, setFifthAgency] = useState(() =>
    agencyDisplayNameToSelectId(issue.fifthAgency, agencyOptions),
  );
  const [issueTitle, setIssueTitle] = useState(issue.issue);
  const [category, setCategory] = useState(issue.category);
  const [issueDescription, setIssueDescription] = useState(issue.issueDescription);
  const [recommendation, setRecommendation] = useState(issue.recommendation);
  const [rgcDecision, setRgcDecision] = useState(issue.rgcDecision);
  const [indicators, setIndicators] = useState(() =>
    getEditableFieldValue(issue.indicators),
  );
  const [progressSolution, setProgressSolution] = useState(() =>
    getEditableFieldValue(issue.progressSolution),
  );
  const [implementationChallenges, setImplementationChallenges] = useState(() =>
    getEditableFieldValue(issue.implementationChallenges),
  );
  const [request, setRequest] = useState(() => getEditableFieldValue(issue.request));
  const [sourceOfVerification, setSourceOfVerification] = useState(() =>
    getEditableFieldValue(issue.sourceOfVerification),
  );
  const [linkToVerificationSource, setLinkToVerificationSource] = useState(() =>
    getEditableFieldValue(issue.linkToVerificationSource),
  );
  const [nextStep, setNextStep] = useState(() => getEditableFieldValue(issue.nextStep));
  const [dateOfIssueSolution, setDateOfIssueSolution] = useState<Date | null>(() =>
    parseIssueSolutionDate(issue.dateOfIssueSolution),
  );
  const [attachment, setAttachment] = useState<File | null>(null);
  const [uploadStatus, setUploadStatus] = useState<UploadStatus>("idle");
  const [uploadError, setUploadError] = useState<string | null>(null);

  function handleFileSelect(file: File) {
    if (file.type !== "application/pdf" && !file.name.toLowerCase().endsWith(".pdf")) {
      setUploadError("Only PDF files are supported.");
      return;
    }

    if (file.size > MAX_PDF_SIZE_BYTES) {
      setUploadError("PDF file must be 10 MB or smaller.");
      return;
    }

    setUploadError(null);
    setAttachment(file);
    setUploadStatus("uploading");
    window.setTimeout(() => setUploadStatus("completed"), 800);
  }

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

  function handleDrop(event: DragEvent<HTMLDivElement>) {
    event.preventDefault();
    const file = event.dataTransfer.files?.[0];
    if (file) handleFileSelect(file);
  }

  function handleDragOver(event: DragEvent<HTMLDivElement>) {
    event.preventDefault();
  }

  function toStoredValue(value: string) {
    const trimmed = value.trim();
    return trimmed || "No data";
  }

  async function handleSave() {
    const selectedStatus = issueStatusOptions.find(
      (option) => option.name.toLowerCase() === status.trim().toLowerCase(),
    );

    if (!selectedStatus) {
      setSaveError("Please select a valid Issue status.");
      return;
    }

    const updatedIssue: MinistryProgressReportIssueRow = {
      ...issue,
      issueStatusId: selectedStatus.id,
      primaryAgency:
        agencySelectIdToDisplayName(primaryAgency, agencyOptions) || issue.primaryAgency,
      primaryAgencyLogo: agencySelectIdToLogo(primaryAgency, agencyOptions),
      pswg,
      status: (status || issue.status) as MinistryProgressReportIssueRow["status"],
      secondAgency:
        agencySelectIdToDisplayName(secondAgency, agencyOptions) || "No data",
      secondAgencyLogo: agencySelectIdToLogo(secondAgency, agencyOptions),
      thirdAgency:
        agencySelectIdToDisplayName(thirdAgency, agencyOptions) || "No data",
      thirdAgencyLogo: agencySelectIdToLogo(thirdAgency, agencyOptions),
      fourthAgency:
        agencySelectIdToDisplayName(fourthAgency, agencyOptions) || "No data",
      fourthAgencyLogo: agencySelectIdToLogo(fourthAgency, agencyOptions),
      fifthAgency:
        agencySelectIdToDisplayName(fifthAgency, agencyOptions) || "No data",
      fifthAgencyLogo: agencySelectIdToLogo(fifthAgency, agencyOptions),
      issue: issueTitle.trim() || issue.issue,
      category: category.trim() || issue.category,
      issueDescription: issueDescription.trim() || issue.issueDescription,
      recommendation: recommendation.trim() || issue.recommendation,
      rgcDecision: rgcDecision.trim() || issue.rgcDecision,
      indicators: toStoredValue(indicators),
      progressSolution: toStoredValue(progressSolution),
      implementationChallenges: toStoredValue(implementationChallenges),
      request: toStoredValue(request),
      sourceOfVerification: toStoredValue(sourceOfVerification),
      linkToVerificationSource: toStoredValue(linkToVerificationSource),
      nextStep: toStoredValue(nextStep),
      dateOfIssueSolution: formatIssueSolutionDate(dateOfIssueSolution),
    };

    setSaveError(null);
    setSaving(true);

    try {
      await onSave?.({
        issue: updatedIssue,
        issueStatusId: selectedStatus.id,
        indicators: indicators.trim() || undefined,
        progressSolution: progressSolution.trim() || undefined,
        implementationChallenges:
          implementationChallenges.trim() || undefined,
        requests: request.trim() || undefined,
        sourceOfVerification: sourceOfVerification.trim() || undefined,
        linkToVerificationSource:
          linkToVerificationSource.trim() || undefined,
        nextStep: nextStep.trim() || undefined,
        dateOfIssueSolution:
          dateOfIssueSolution && isValid(dateOfIssueSolution)
            ? format(dateOfIssueSolution, "yyyy-MM-dd")
            : undefined,
        attachment,
      });
      onClose();
    } catch (error) {
      setSaveError(
        error instanceof Error
          ? error.message
          : "Unable to save the progress update.",
      );
    } finally {
      setSaving(false);
    }
  }

  const inputSx = getDialogInputSx(theme);
  const selectSx = getDialogSelectSx(theme);
  // Selects still render with their normal (non-grayed) styling in read-only
  // mode; hiding the dropdown arrow keeps them from looking clickable.
  const readOnlySelectFieldSx = {
    pointerEvents: "none" as const,
    "& .MuiSelect-icon": { display: "none" },
  };

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        height: "100%",
        minHeight: 0,
      }}
    >
      <Box
        sx={{
          height: 67,
          px: "22px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          borderBottom: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#e9eaeb"}`,
          flexShrink: 0,
        }}
      >
        <Typography
          sx={{
            fontSize: 20,
            fontWeight: 500,
            color: "#0a0a0a",
            letterSpacing: "-0.4px",
            lineHeight: 1.2,
          }}
        >
          {readOnly ? "Issue Info" : "Update Issue"}
        </Typography>

        <IconButton onClick={onClose} size="small" sx={{ color: "#717680" }}>
          <CloseIcon sx={{ fontSize: 24 }} />
        </IconButton>
      </Box>

      <Box
        sx={{
          px: "18px",
          py: "22px",
          overflowY: "auto",
          flex: 1,
          minHeight: 0,
        }}
      >
        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: { xs: "1fr", md: "1fr 1fr 1fr" },
            gap: "22px",
            mb: "22px",
          }}
        >
          <Box sx={readOnly ? readOnlySelectFieldSx : undefined}>
            <AgencySelect
              agencies={agencyOptions}
              emptyLabel={readOnly ? "" : undefined}
              label="Government Primary Agency"
              value={primaryAgency}
              onChange={setPrimaryAgency}
              menuProps={selectMenuProps}
            />
          </Box>

          <Box sx={readOnly ? readOnlySelectFieldSx : undefined}>
            <DialogFieldLabel>Private Sector Working Group</DialogFieldLabel>
            <Select
              fullWidth
              value={pswg}
              onChange={(event) => setPswg(event.target.value)}
              sx={selectSx}
              MenuProps={selectMenuProps}
            >
              {[pswg, ...PSWG_OPTIONS]
                .filter(
                  (option, index, options) =>
                    Boolean(option) && options.indexOf(option) === index,
                )
                .map((option) => (
                  <MenuItem key={option} value={option} sx={{ fontSize: 12 }}>
                    {option}
                  </MenuItem>
                ))}
            </Select>
          </Box>

          <Box sx={readOnly ? readOnlySelectFieldSx : undefined}>
            <DialogFieldLabel>Status</DialogFieldLabel>
            <IssueStatusSelect
              value={status}
              placeholder={readOnly ? "" : undefined}
              menuZIndex={SELECT_MENU_Z_INDEX}
              onChange={setStatus}
              sx={{
                width: "100%",
                height: 40,
                minWidth: 0,
                bgcolor: theme.palette.background.paper,
                "& .MuiSelect-select": {
                  height: 40,
                  minHeight: "40px !important",
                  py: 0,
                  display: "flex",
                  alignItems: "center",
                },
              }}
            />
          </Box>
        </Box>

        <Box
          sx={
            readOnly
              ? { mb: "22px", ...readOnlySelectFieldSx }
              : { mb: "22px" }
          }
        >
          <AdditionalAgencyFields
            agencies={agencyOptions}
            emptyLabel={readOnly ? "" : undefined}
            secondAgency={secondAgency}
            onSecondAgencyChange={setSecondAgency}
            thirdAgency={thirdAgency}
            onThirdAgencyChange={setThirdAgency}
            fourthAgency={fourthAgency}
            onFourthAgencyChange={setFourthAgency}
            fifthAgency={fifthAgency}
            onFifthAgencyChange={setFifthAgency}
            selectMenuProps={selectMenuProps}
          />
        </Box>

        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
            gap: "22px",
            mb: "42px",
          }}
        >
          <Box>
            <DialogFieldLabel>Issue</DialogFieldLabel>
            <TextField
              fullWidth
              value={issueTitle}
              onChange={(event) => setIssueTitle(event.target.value)}
              sx={inputSx}
              slotProps={{ input: { readOnly } }}
            />
          </Box>

          <Box>
            <DialogFieldLabel>Category of Issues</DialogFieldLabel>
            <TextField
              fullWidth
              value={category}
              onChange={(event) => setCategory(event.target.value)}
              sx={inputSx}
              slotProps={{ input: { readOnly } }}
            />
          </Box>
        </Box>

        <Box sx={{ display: "grid", gap: "42px" }}>
          <IssueEditorField
            label="Issue Description"
            placeholder="Write issue description........."
            readOnly={readOnly}
            value={issueDescription}
            onChange={setIssueDescription}
          />
          <IssueEditorField
            label="Recommendation"
            placeholder="Write recommendation........."
            readOnly={readOnly}
            value={recommendation}
            onChange={setRecommendation}
          />
          <IssueEditorField
            label="RGC Decision"
            placeholder="Write RGC Decision........."
            readOnly={readOnly}
            value={rgcDecision}
            onChange={setRgcDecision}
          />
          <IssueEditorField
            label="Indicators"
            placeholder="Write indicators........."
            readOnly={readOnly}
            value={indicators}
            onChange={setIndicators}
          />
          <IssueEditorField
            label="Progress Solution"
            placeholder="Write progress solution........."
            readOnly={readOnly}
            value={progressSolution}
            onChange={setProgressSolution}
          />
          <IssueEditorField
            label="Implementation Challenges"
            placeholder="Write implementation challenges........."
            readOnly={readOnly}
            value={implementationChallenges}
            onChange={setImplementationChallenges}
          />
          <IssueEditorField
            label="Requests"
            placeholder="Write requests........."
            readOnly={readOnly}
            value={request}
            onChange={setRequest}
          />
          <IssueEditorField
            label="Source of Verification"
            placeholder="Write source of verification........."
            readOnly={readOnly}
            value={sourceOfVerification}
            onChange={setSourceOfVerification}
          />
          <Box>
            <DialogFieldLabel>Link to Verification Source</DialogFieldLabel>
            <TextField
              fullWidth
              value={linkToVerificationSource}
              onChange={(event) =>
                setLinkToVerificationSource(event.target.value)
              }
              placeholder={
                readOnly ? "" : "Enter Link to Verification Source"
              }
              slotProps={{ input: { readOnly } }}
              sx={{
                ...inputSx,
                "& .MuiInputBase-input": {
                  fontSize: 13,
                  fontWeight: 500,
                  py: 0,
                  "&::placeholder": {
                    color: "#717680",
                    opacity: 1,
                  },
                },
                "& .MuiOutlinedInput-root fieldset": {
                  borderColor: "#d5d7da",
                },
              }}
            />
          </Box>
          <IssueEditorField
            label="Next Step"
            placeholder="Write next step........."
            readOnly={readOnly}
            value={nextStep}
            onChange={setNextStep}
          />

          <Box
            sx={
              readOnly
                ? { maxWidth: 238, pointerEvents: "none" }
                : { maxWidth: 238 }
            }
          >
            <DialogFieldLabel>Date of Issue Solution</DialogFieldLabel>
            <AppDatePicker
              value={dateOfIssueSolution}
              onChange={setDateOfIssueSolution}
              placeholder={readOnly ? "" : "Select date"}
              popperZIndex={PICKER_Z_INDEX}
            />
          </Box>

          {readOnly ? (
            <ReadOnlyAttachmentField attachment={issueAttachment} />
          ) : (
            <Box sx={{ maxWidth: 375 }}>
              <DialogFieldLabel>Attachment</DialogFieldLabel>
              <IssuesReferenceUploadField
                attachment={attachment}
                existingReference={
                  issueAttachment
                    ? {
                        name: issueAttachment.name,
                        size: formatFileSize(issueAttachment.size),
                        path: issueAttachment.path,
                      }
                    : null
                }
                fileInputRef={fileInputRef}
                uploadStatus={uploadStatus}
                onDragOver={handleDragOver}
                onDrop={handleDrop}
                onFileChange={handleFileChange}
                onUploadClick={() => fileInputRef.current?.click()}
              />
              {uploadError ? (
                <Typography sx={{ mt: 1, fontSize: 12, color: "#f04438" }}>
                  {uploadError}
                </Typography>
              ) : null}
            </Box>
          )}

          {saveError ? <Alert severity="error">{saveError}</Alert> : null}
        </Box>
      </Box>

      {!readOnly || onAddComment ? (
        <Box
          sx={{
            height: 84,
            px: "22px",
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-end",
            borderTop: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#ddedfb"}`,
            flexShrink: 0,
            bgcolor: isDark ? "#101828" : "#ffffff",
          }}
        >
          <AppButton
            disabled={!readOnly && saving}
            onClick={() => (readOnly ? onAddComment?.() : void handleSave())}
            sx={{
              minWidth: 150,
              width: 150,
              height: 40,
              bgcolor: "#1a64a8",
              "&:hover": { bgcolor: "#155a96" },
            }}
          >
            {readOnly ? "Add Comment" : saving ? "Saving..." : "Save"}
          </AppButton>
        </Box>
      ) : null}
    </Box>
  );
}

function ProgressReportIssueDrawerShell({
  open,
  issue,
  onClose,
  children,
}: {
  open: boolean;
  issue: MinistryProgressReportIssueRow | null;
  onClose: () => void;
  children: ReactNode;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Drawer
      anchor="right"
      open={open && Boolean(issue)}
      onClose={onClose}
      sx={{
        zIndex: DRAWER_Z_INDEX,
        "& .MuiBackdrop-root": { bgcolor: "rgba(0, 0, 0, 0.35)" },
        "& .MuiDrawer-paper": {
          width: { xs: "100vw", sm: 795 },
          maxWidth: "100vw",
          height: "100dvh",
          borderRadius: "12px 0 0 12px",
          overflow: "hidden",
          bgcolor: isDark ? "#101828" : "#ffffff",
          backgroundImage: "none",
          display: "flex",
          flexDirection: "column",
        },
      }}
    >
      {issue ? children : null}
    </Drawer>
  );
}

export function ProgressReportIssueInfoDrawer({
  open,
  issue,
  onClose,
  onAddComment,
  issueAttachment,
}: Pick<Props, "open" | "issue" | "onClose" | "onAddComment" | "issueAttachment">) {
  return (
    <UpdateProgressReportIssueDialog
      open={open}
      issue={issue}
      onClose={onClose}
      onAddComment={onAddComment}
      issueAttachment={issueAttachment}
      readOnly
    />
  );
}

export function UpdateProgressReportIssueDialog({
  open,
  issue,
  onClose,
  onSave,
  readOnly = false,
  onAddComment,
  issueAttachment,
}: Props) {
  return (
    <ProgressReportIssueDrawerShell open={open} issue={issue} onClose={onClose}>
      {issue ? (
        <UpdateProgressReportIssueDialogContent
          key={issue.id}
          issue={issue}
          onClose={onClose}
          onSave={onSave}
          readOnly={readOnly}
          onAddComment={onAddComment}
          issueAttachment={issueAttachment}
        />
      ) : null}
    </ProgressReportIssueDrawerShell>
  );
}
