"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

import MoreVertIcon from "@mui/icons-material/MoreVert";
import UploadFileOutlinedIcon from "@mui/icons-material/UploadFileOutlined";
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import { useAppLanguage } from "@/components/providers/app-language-provider";
import { AlertDialog } from "@/components/ui/alert-dialog";
import { DocumentLink } from "@/components/ui/document-link";
import { PencilEditIcon } from "@/components/ui/icon";
import { PdfDocumentIcon } from "@/components/ui/pdf-document-icon";
import {
  formatDocumentCellValue,
  isDocumentPlaceholder,
  truncateFileName,
} from "@/lib/document-file";
import { formatNumber } from "@/lib/number-utils";

import { MeetingSummaryStatusBadge } from "@/components/ui/meeting-summary-status-badge";

import {
  meetingSummaryStatusLabels,
  type MeetingSummaryRow,
  type MeetingSummaryStatus,
} from "../meeting-summary-data";
import { updateMeetingSummary } from "../meeting-summary-service";
import { meetingSummaryI18n, type UiLang } from "../meeting-summary-i18n";

export function SummaryTitleCell({ value }: { value: string }) {
  return (
    <Typography
      className="font-kh"
      sx={{
        width: "100%",
        overflow: "hidden",
        textOverflow: "ellipsis",
        fontSize: 13,
        fontWeight: 500,
        color: "var(--ms-text, #181d27)",
        whiteSpace: "nowrap",
      }}
    >
      {value}
    </Typography>
  );
}

export function SummaryTextCell({
  value,
  align = "left",
  fontWeight = 500,
  wrap = false,
}: {
  value: string;
  align?: "left" | "center" | "right";
  fontWeight?: number;
  wrap?: boolean;
}) {
  return (
    <Typography
      sx={{
        width: "100%",
        overflow: "hidden",
        textOverflow: wrap ? "clip" : "ellipsis",
        fontSize: 13,
        fontWeight,
        color: "var(--ms-text, #181d27)",
        whiteSpace: wrap ? "normal" : "nowrap",
        textAlign: align,
        lineHeight: wrap ? 1.35 : 1.2,
        display: wrap ? "-webkit-box" : "block",
        WebkitLineClamp: wrap ? 2 : "unset",
        WebkitBoxOrient: wrap ? "vertical" : "unset",
        wordBreak: wrap ? "break-word" : "normal",
      }}
    >
      {value}
    </Typography>
  );
}

export function IssueCountCell({ count }: { count: number }) {
  const { language } = useAppLanguage();
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box
      sx={{
        width: 30,
        height: 30,
        borderRadius: "50%",
        bgcolor: isDark ? "#3B2B3A" : "var(--ms-red-bg, #FFFBFA)",
        color: isDark ? "#FCA5A5" : "var(--ms-red-text, #F04438)",
        fontSize: 13,
        fontWeight: 500,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        flexShrink: 0,
      }}
    >
      {formatNumber(count, language)}
    </Box>
  );
}

export function MeetingDocumentCell({
  label,
}: {
  label: string;
  wrap?: boolean;
}) {
  const theme = useTheme();
  const hasDocument = !isDocumentPlaceholder(label);
  const displayLabel = formatDocumentCellValue(label, "-");
  const shortLabel = hasDocument ? truncateFileName(displayLabel) : displayLabel;

  return (
    <Box
      onClick={(event) => event.stopPropagation()}
      onMouseDown={(event) => event.stopPropagation()}
      sx={{
        width: "100%",
        height: "100%",
        minWidth: 0,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <DocumentLink
        file={hasDocument ? { path: label } : null}
        sx={{
          maxWidth: "100%",
          minWidth: 0,
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 0.75,
          overflow: "hidden",
        }}
      >
        {hasDocument ? <PdfDocumentIcon size={20} /> : null}

        <Typography
          sx={{
            color: theme.palette.text.primary,
            fontSize: 13,
            lineHeight: 1.5,
            minWidth: 0,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {shortLabel}
        </Typography>
      </DocumentLink>
    </Box>
  );
}

export function GovernmentAgencyCell({
  name,
  logo,
}: {
  name: string;
  logo?: string | null;
}) {
  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: 1, minWidth: 0 }}>
      <Avatar
        src={logo ?? undefined}
        alt={name}
        sx={{
          width: 35,
          height: 35,
          bgcolor: "#f3f4f6",
          fontSize: 10,
          fontWeight: 600,
          flexShrink: 0,
        }}
      >
        {name.slice(0, 2)}
      </Avatar>
      <Typography
        noWrap
        sx={{
          fontSize: 12,
          fontWeight: 500,
          color: "var(--ms-text, #181d27)",
        }}
      >
        {name}
      </Typography>
    </Box>
  );
}

export function SummaryStatusCell({ status }: { status: MeetingSummaryStatus }) {
  return (
    <MeetingSummaryStatusBadge
      status={status}
      label={meetingSummaryStatusLabels[status]}
    />
  );
}

function hasMeetingSummaryReference(value: string) {
  return !isDocumentPlaceholder(value);
}

export function SummaryActionCell({
  row,
  lang = "en",
  onSubmitReportSuccess,
  onRowUpdated,
}: {
  row: MeetingSummaryRow;
  lang?: UiLang;
  onSubmitReportSuccess?: () => void;
  onRowUpdated?: (id: number, status: MeetingSummaryStatus) => void;
}) {
  const router = useRouter();
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const t = meetingSummaryI18n[lang];
  const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);
  const [submitDialogOpen, setSubmitDialogOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const showEditAndSubmit =
    row.status === "DRAFT" || row.status === "REVIEWED";
  const showSubmitReport =
    showEditAndSubmit && hasMeetingSummaryReference(row.meetingSummary);

  function closeMenu() {
    setMenuAnchor(null);
  }

  function handleEdit() {
    closeMenu();
    router.push(`/ministry/meeting-summary/${row.id}/edit`);
  }

  function handleViewDetail() {
    closeMenu();
    router.push(`/ministry/meeting-summary/${row.id}`);
  }

  function handleSubmitReportClick() {
    closeMenu();
    setSubmitError(null);
    setSubmitDialogOpen(true);
  }

  async function handleSubmitConfirm() {
    setSubmitting(true);
    setSubmitError(null);

    try {
      await updateMeetingSummary(row.id, { status: "SUBMITTED" });
      onRowUpdated?.(row.id, "SUBMITTED");
      onSubmitReportSuccess?.();
      setSubmitDialogOpen(false);
    } catch (error) {
      setSubmitError(
        error instanceof Error
          ? error.message
          : "Could not submit meeting summary.",
      );
    } finally {
      setSubmitting(false);
    }
  }

  const menuItemSx = {
    gap: 1.25,
    px: 2,
    py: 1.25,
    fontSize: 14,
    color: isDark ? alpha("#ffffff", 0.78) : "#414651",
    "& .MuiListItemIcon-root": {
      minWidth: 0,
      color: "inherit",
    },
  };

  return (
    <>
      <IconButton
        size="small"
        aria-label="More actions"
        onClick={(event) => setMenuAnchor(event.currentTarget)}
        sx={{
          width: 32,
          height: 32,
          color: isDark ? alpha("#ffffff", 0.55) : "#717680",
          "&:hover": {
            bgcolor: isDark
              ? alpha("#ffffff", 0.06)
              : alpha("#000000", 0.04),
          },
        }}
      >
        <MoreVertIcon sx={{ fontSize: 20 }} />
      </IconButton>

      <Menu
        anchorEl={menuAnchor}
        open={Boolean(menuAnchor)}
        onClose={closeMenu}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
        slotProps={{
          paper: {
            sx: {
              minWidth: 200,
              borderRadius: "10px",
              boxShadow: isDark
                ? "0 0 20px rgba(0,0,0,0.45)"
                : "0 4px 16px rgba(0,0,0,0.12)",
            },
          },
        }}
      >
        <MenuItem onClick={handleViewDetail} sx={menuItemSx}>
          <ListItemIcon>
            <VisibilityOutlinedIcon sx={{ fontSize: 20 }} />
          </ListItemIcon>
          {showEditAndSubmit ? t.viewDetails : t.viewDetail}
        </MenuItem>

        {showEditAndSubmit ? (
          <MenuItem onClick={handleEdit} sx={menuItemSx}>
            <ListItemIcon>
              <PencilEditIcon sx={{ fontSize: 20 }} />
            </ListItemIcon>
            {t.edit}
          </MenuItem>
        ) : null}

        {showSubmitReport ? (
          <MenuItem onClick={handleSubmitReportClick} sx={menuItemSx}>
            <ListItemIcon>
              <UploadFileOutlinedIcon sx={{ fontSize: 20 }} />
            </ListItemIcon>
            {t.submitReport}
          </MenuItem>
        ) : null}
      </Menu>

      <AlertDialog
        open={submitDialogOpen}
        title="Submit to CDC"
        description={
          submitError ? (
            <>
              Are you sure you want to submit to CDC?
              <Box
                component="span"
                sx={{ display: "block", mt: 1, color: "#d92d20", fontSize: 13 }}
              >
                {submitError}
              </Box>
            </>
          ) : (
            "Are you sure you want to submit to CDC?"
          )
        }
        confirmLabel="Submit"
        cancelLabel="Cancel"
        loading={submitting}
        onConfirm={handleSubmitConfirm}
        onCancel={() => {
          if (submitting) return;
          setSubmitDialogOpen(false);
          setSubmitError(null);
        }}
      />
    </>
  );
}
