"use client";

// Detail popup that opens when a calendar event card is clicked
// (Figma node 38506:483060). Shows the meeting date/time, location,
// description, and the meeting request document. Read-only.

import { useEffect, useState } from "react";

import CloseIcon from "@mui/icons-material/Close";
import Box from "@mui/material/Box";
import Dialog from "@mui/material/Dialog";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import { useAppLanguage } from "@/components/providers/app-language-provider";
import { DocumentFileName } from "@/components/ui/document-file-name";
import { DocumentLink } from "@/components/ui/document-link";
import {
  CalendarIcon,
  LocationOnIcon,
  PdfIcon,
  TimeIcon,
  WarningIcon,
} from "@/components/ui/icon";
import { IssueStatusBadge } from "@/components/ui/issue-status-badge";
import {
  formatCalendarDate,
  formatCalendarTimeText,
} from "@/components/ui/month-calendar";
import { formatFileSize } from "@/lib/document-file";

import type {
  ProgressReportCalendarEvent,
  ProgressReportCalendarEventDetail,
} from "../../progress-report-calendar-data";
import { mapProgressReportMeetingDetailToCalendarEvent } from "../../progress-report-calendar-mapper";
import { getProgressReportMeeting } from "../../service/progress-report-service";
import {
  normalizeProgressReportLanguage,
  translateProgressReportValue,
  type ProgressReportEventDialogLabels,
} from "../../progress-report-i18n";

type ProgressReportEventDialogProps = {
  event: ProgressReportCalendarEvent | null;
  labels: ProgressReportEventDialogLabels;
  onClose: () => void;
};

// A muted "Label :" followed by its bold value, with an icon in front.
function DetailItem({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: 1, minWidth: 0 }}>
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          flexShrink: 0,
          color: isDark ? "#98a2b3" : "#717680",
        }}
      >
        {icon}
      </Box>
      <Typography
        sx={{
          flexShrink: 0,
          fontSize: 13,
          fontWeight: 400,
          color: isDark ? "#d0d5dd" : "#717680",
          whiteSpace: "nowrap",
        }}
      >
        {label} :
      </Typography>
      <Typography
        sx={{
          fontSize: 13,
          fontWeight: 600,
          color: isDark ? "#f9fafb" : "#181d27",
          whiteSpace: "nowrap",
        }}
      >
        {value}
      </Typography>
    </Box>
  );
}

function hasDisplayValue(value?: string | null) {
  const trimmed = value?.trim();
  return Boolean(trimmed && trimmed !== "-");
}

export function ProgressReportEventDialog({
  event,
  labels,
  onClose,
}: ProgressReportEventDialogProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const { language } = useAppLanguage();
  const pageLanguage = normalizeProgressReportLanguage(language);
  // Keeping the meeting id next to the fetched detail means a stale response
  // is simply ignored instead of having to be cleared on every open.
  const [loadedDetail, setLoadedDetail] = useState<{
    meetingId: number;
    detail: ProgressReportCalendarEventDetail;
  } | null>(null);

  // The report list only carries lightweight meetings, so the location,
  // description and document are fetched when a card is opened.
  useEffect(() => {
    if (!event) return;

    let active = true;
    const meetingId = event.id;

    getProgressReportMeeting(meetingId)
      .then((meeting) => {
        if (active) {
          setLoadedDetail({
            meetingId,
            detail: mapProgressReportMeetingDetailToCalendarEvent(meeting),
          });
        }
      })
      .catch(() => {
        // A failed lookup just leaves the placeholder dashes in place.
      });

    return () => {
      active = false;
    };
  }, [event]);

  const detail =
    event && loadedDetail?.meetingId === event.id ? loadedDetail.detail : null;

  const sectionTitleSx = {
    fontSize: 16,
    fontWeight: 700,
    color: isDark ? "#f9fafb" : "#181d27",
  } as const;

  const softCardSx = {
    borderRadius: "8px",
    bgcolor: isDark ? alpha("#ffffff", 0.04) : "#fafafa",
  } as const;

  return (
    <Dialog
      open={Boolean(event)}
      onClose={onClose}
      maxWidth={false}
      scroll="paper"
      sx={{ "& .MuiBackdrop-root": { bgcolor: "rgba(0,0,0,0.45)" } }}
      slotProps={{
        paper: {
          sx: {
            width: { xs: "calc(100vw - 32px)", md: 640 },
            maxWidth: "calc(100vw - 32px)",
            maxHeight: "calc(100dvh - 34px)",
            borderRadius: "12px",
            bgcolor: isDark ? "#101828" : "#ffffff",
            backgroundImage: "none",
            overflow: "hidden",
          },
        },
      }}
    >
      {event ? (
        <>
          {/* Title + close button */}
          <Box
            sx={{
              px: 3,
              pt: 2.5,
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              gap: 2,
            }}
          >
            <Typography
              sx={{
                fontSize: 20,
                fontWeight: 600,
                letterSpacing: "-0.4px",
                color: isDark ? "#f9fafb" : "#181d27",
              }}
            >
              {event.title}
            </Typography>
            <IconButton
              onClick={onClose}
              size="small"
              aria-label={labels.closeDialog}
              sx={{ color: isDark ? "#d0d5dd" : "#717680" }}
            >
              <CloseIcon sx={{ fontSize: 20 }} />
            </IconButton>
          </Box>

          {/* "Meeting Details" tab with its blue underline */}
          <Box
            sx={{
              px: 3,
              mt: 2,
              borderBottom: `1px solid ${theme.palette.divider}`,
            }}
          >
            <Box
              sx={{
                display: "inline-block",
                pb: 1,
                borderBottom: "2px solid #1a64a8",
              }}
            >
              <Typography
                sx={{ fontSize: 13, fontWeight: 500, color: "#1a64a8" }}
              >
                {labels.meetingDetailsTab}
              </Typography>
            </Box>
          </Box>

          {/* Scrollable body */}
          <Box sx={{ px: 3, py: 2.5, overflowY: "auto" }}>
            {/* Date + start/end time on one row */}
            <Box
              sx={{
                display: "flex",
                flexWrap: "wrap",
                alignItems: "center",
                columnGap: 3,
                rowGap: 1.5,
              }}
            >
              <DetailItem
                icon={<CalendarIcon sx={{ fontSize: 20 }} />}
                label={labels.meetingDate}
                value={formatCalendarDate(event.dateKey, language)}
              />
              <DetailItem
                icon={<TimeIcon sx={{ fontSize: 20 }} />}
                label={labels.startTime}
                value={formatCalendarTimeText(event.startTime, language)}
              />
              <DetailItem
                icon={<TimeIcon sx={{ fontSize: 20 }} />}
                label={labels.endTime}
                value={formatCalendarTimeText(event.endTime, language)}
              />
            </Box>

            {/* Location + status share one grid so icons, labels, and values align */}
            <Box
              sx={{
                mt: 2,
                display: "grid",
                gridTemplateColumns: "20px max-content minmax(0, 1fr)",
                columnGap: 1,
                rowGap: 2,
                alignItems: "center",
              }}
            >
              <Box
                sx={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  color: isDark ? "#98a2b3" : "#717680",
                }}
              >
                <LocationOnIcon sx={{ fontSize: 20 }} />
              </Box>
              <Typography
                sx={{
                  fontSize: 13,
                  fontWeight: 400,
                  color: isDark ? "#d0d5dd" : "#717680",
                  whiteSpace: "nowrap",
                }}
              >
                {labels.location} :
              </Typography>
              {hasDisplayValue(detail?.locationName ?? "-") ||
              hasDisplayValue(detail?.locationAddress ?? "-") ? (
                <Box sx={{ minWidth: 0 }}>
                  {hasDisplayValue(detail?.locationName ?? "-") ? (
                    <Typography
                      sx={{
                        fontSize: 13,
                        fontWeight: 600,
                        color: isDark ? "#f9fafb" : "#181d27",
                      }}
                    >
                      {detail?.locationName ?? "-"}
                    </Typography>
                  ) : null}
                  {hasDisplayValue(detail?.locationAddress ?? "-") ? (
                    <Typography
                      sx={{
                        mt: hasDisplayValue(detail?.locationName ?? "-")
                          ? 0.25
                          : 0,
                        fontSize: 11,
                        color: isDark ? "#98a2b3" : "#717680",
                      }}
                    >
                      {detail?.locationAddress ?? "-"}
                    </Typography>
                  ) : null}
                </Box>
              ) : (
                <Box />
              )}

              <Box
                sx={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  color: isDark ? "#98a2b3" : "#717680",
                }}
              >
                <WarningIcon sx={{ fontSize: 20 }} />
              </Box>
              <Typography
                sx={{
                  fontSize: 13,
                  fontWeight: 400,
                  color: isDark ? "#d0d5dd" : "#717680",
                  whiteSpace: "nowrap",
                }}
              >
                {labels.status} :
              </Typography>
              <Box sx={{ display: "flex", alignItems: "center" }}>
                <IssueStatusBadge
                  status={detail?.status ?? event.status}
                  label={translateProgressReportValue(
                    detail?.status ?? event.status,
                    pageLanguage,
                  )}
                />
              </Box>
            </Box>

            {/* Description */}
            <Typography sx={{ ...sectionTitleSx, mt: 3, mb: 1.5 }}>
              {labels.description}
            </Typography>
            <Box sx={{ ...softCardSx, px: 2.5, py: 2 }}>
              <Typography
                sx={{
                  fontSize: 13,
                  fontWeight: 400,
                  lineHeight: 1.6,
                  color: isDark ? "#e5e7eb" : "#181d27",
                }}
              >
                {(detail?.description ?? "-")}
              </Typography>
            </Box>

            {/* Meeting request document */}
            <Typography sx={{ ...sectionTitleSx, mt: 3, mb: 1.5 }}>
              {labels.meetingRequestDocument}
            </Typography>
            <DocumentLink
              file={(detail?.document ?? null)}
              sx={{
                ...softCardSx,
                display: "inline-flex",
                alignItems: "center",
                gap: 1.5,
                px: 2,
                py: 1.5,
                minWidth: 280,
              }}
            >
              <PdfIcon sx={{ fontSize: 28 }} />
              <Box sx={{ minWidth: 0 }}>
                <DocumentFileName
                  name={(detail?.documentName ?? "-")}
                  fontSize={12}
                  fontWeight={500}
                  color={isDark ? "#f9fafb" : "#252b37"}
                />
                <Typography
                  sx={{
                    mt: 0.25,
                    fontSize: 10,
                    color: isDark ? "#98a2b3" : "#717680",
                  }}
                >
                  {formatFileSize(detail?.documentSize ?? null, language)}
                </Typography>
              </Box>
            </DocumentLink>
          </Box>
        </>
      ) : null}
    </Dialog>
  );
}
