import Box from "@mui/material/Box";
import ButtonBase from "@mui/material/ButtonBase";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import { dashboardAssets } from "@/components/dashboard/dashboard-assets";
import { DashboardAssetIcon } from "@/components/dashboard/dashboard-asset-icon";
import { DocumentLink } from "@/components/ui/document-link";
import { MeetingRequestStatusBadge } from "@/components/ui/meeting-request-status-badge";
import { PdfDocumentIcon } from "@/components/ui/pdf-document-icon";
import {
  formatDocumentCellValue,
  isDocumentPlaceholder,
  truncateFileName,
} from "@/lib/document-file";
import {
  getMeetingRequestFont,
  i18n,
  type UiLang,
} from "@/features/pswg/meeting-request/meeting-request-i18n";
import type { MeetingRequestStatus } from "@/features/pswg/meeting-request/meeting-request-data";

function resolveAssetUrl(value?: string | null) {
  if (!value) return "";

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

  const apiBaseUrl = (
    process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001/api/v1"
  )
    .replace(/\/api\/v\d+$/, "")
    .replace(/\/$/, "");

  if (value.startsWith("/")) {
    return `${apiBaseUrl}${value}`;
  }

  return value;
}

export function TableText({
  value,
  align = "left",
  fontFamily,
}: {
  value: string;
  align?: "left" | "center" | "right";
  fontFamily?: string;
}) {
  const theme = useTheme();

  return (
    <Typography
      sx={{
        width: "100%",
        color: theme.palette.text.primary,
        fontSize: 13,
        lineHeight: 1.5,
        whiteSpace: "nowrap",
        overflow: "hidden",
        textOverflow: "ellipsis",
        textAlign: align,
        fontFamily,
      }}
    >
      {value}
    </Typography>
  );
}

export function StatusBadge({
  status,
  language = "km",
}: {
  status: MeetingRequestStatus;
  language?: UiLang;
}) {
  const t = i18n(language);

  return (
    <MeetingRequestStatusBadge
      status={status}
      label={t.statuses[status]}
      sx={{
        "& .MuiTypography-root": {
          fontFamily: getMeetingRequestFont(language),
        },
      }}
    />
  );
}

export function AgencyCell({
  agency,
  logo,
  logoSize = 24,
}: {
  agency: string;
  logo?: string | null;
  logoSize?: number;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const logoUrl = resolveAssetUrl(logo);

  return (
    <Box
      sx={{
        width: "100%",
        display: "flex",
        alignItems: "center",
        justifyContent: "flex-start",
        gap: 1,
        minWidth: 0,
      }}
    >
      {logoUrl ? (
        <Box
          component="img"
          src={logoUrl}
          alt={agency}
          onError={(event) => {
            event.currentTarget.style.display = "none";
          }}
          sx={{
            width: logoSize,
            height: logoSize,
            borderRadius: "50%",
            objectFit: "cover",
            flexShrink: 0,
            border: `1px solid ${alpha(theme.palette.divider, 0.8)}`,
            bgcolor: isDark
              ? alpha(theme.palette.primary.main, 0.14)
              : "#E8F4FF",
          }}
        />
      ) : (
        <DashboardAssetIcon
          src={dashboardAssets.primaryAgencyAvatar}
          width={logoSize}
          height={logoSize}
        />
      )}

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

export function MeetingRequestCell({
  label,
  wrap = false,
}: {
  label: string;
  wrap?: boolean;
  compact?: 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>
  );
}

function ViewDetailIcon() {
  return (
    <Box component="svg" width={24} height={24} viewBox="0 0 24 24" fill="none">
      <path
        d="M2.25 12C2.25 12 5.25 5.25 12 5.25C18.75 5.25 21.75 12 21.75 12C21.75 12 18.75 18.75 12 18.75C5.25 18.75 2.25 12 2.25 12Z"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <path
        d="M12 14.25C13.2426 14.25 14.25 13.2426 14.25 12C14.25 10.7574 13.2426 9.75 12 9.75C10.7574 9.75 9.75 10.7574 9.75 12C9.75 13.2426 10.7574 14.25 12 14.25Z"
        stroke="currentColor"
        strokeWidth="1.5"
      />
    </Box>
  );
}

export function ViewDetailAction({
  label,
  language = "km",
  onClick,
}: {
  label: string;
  language?: UiLang;
  onClick?: () => void;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <ButtonBase
      onClick={(event) => {
        event.stopPropagation();
        onClick?.();
      }}
      sx={{
        display: "flex",
        alignItems: "center",
        gap: 0.5,
        color: isDark ? alpha("#ffffff", 0.72) : "#717680",
        borderRadius: "6px",
        px: 0.5,
        py: 0.25,
      }}
    >
      <ViewDetailIcon />
      <Typography
        sx={{
          fontSize: 12,
          fontWeight: 400,
          lineHeight: 1.24,
          color: "inherit",
          whiteSpace: "nowrap",
          fontFamily: getMeetingRequestFont(language),
        }}
      >
        {label}
      </Typography>
    </ButtonBase>
  );
}
