import { useState } from "react";

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 type { CdcGpsfMeetingRequestStatus } from "@/features/cdc-gpsf/meeting-requests/cdc-gpsf-meeting-request-data";
import {
  cdcGpsfMeetingRequestI18n,
  getCdcGpsfMeetingRequestFont,
  type CdcGpsfMeetingRequestUiLang,
} from "@/features/cdc-gpsf/meeting-requests/cdc-gpsf-meeting-request-i18n";
import { resolveAssetUrl } from "@/features/cdc-gpsf/meeting-requests/service/cdc-gpsf-meeting-request-service";

export function TableText({
  value,
  fontSize = 13,
  fontWeight = 400,
  align = "left",
  fontFamily,
  wrap = false,
}: {
  value: string;
  fontSize?: number;
  fontWeight?: number;
  align?: "left" | "center" | "right";
  fontFamily?: string;
  wrap?: boolean;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  if (wrap) {
    return (
      <Box
        component="span"
        sx={{
          display: "block",
          width: "100%",
          color: isDark ? alpha("#ffffff", 0.86) : "#181d27",
          fontSize,
          fontWeight,
          lineHeight: 1.35,
          textAlign: align,
          fontFamily,
          whiteSpace: "normal",
          wordBreak: "break-word",
          overflow: "visible",
        }}
      >
        {value}
      </Box>
    );
  }

  return (
    <Typography
      noWrap
      title={value}
      sx={{
        width: "100%",
        color: isDark ? alpha("#ffffff", 0.86) : "#181d27",
        fontSize,
        fontWeight,
        lineHeight: "20px",
        textAlign: align,
        fontFamily,
        overflow: "hidden",
        textOverflow: "ellipsis",
      }}
    >
      {value}
    </Typography>
  );
}

export function StatusBadge({
  status,
  language = "km",
}: {
  status: CdcGpsfMeetingRequestStatus;
  language?: CdcGpsfMeetingRequestUiLang;
}) {
  const t = cdcGpsfMeetingRequestI18n(language);

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

function AgencyLogo({
  logoUrl,
  agency,
  logoSize,
}: {
  logoUrl: string;
  agency: string;
  logoSize: number;
}) {
  const [imageError, setImageError] = useState(false);

  if (imageError) {
    return (
      <DashboardAssetIcon
        src={dashboardAssets.primaryAgencyAvatar}
        width={logoSize}
        height={logoSize}
        sx={{ flexShrink: 0 }}
      />
    );
  }

  return (
    <Box
      component="img"
      src={logoUrl}
      alt={agency}
      onError={() => setImageError(true)}
      sx={{
        width: logoSize,
        height: logoSize,
        borderRadius: "50%",
        objectFit: "cover",
        flexShrink: 0,
      }}
    />
  );
}

export function AgencyCell({
  agency,
  logo,
  logoSize = 30,
  wrap = false,
}: {
  agency: string;
  logo?: string | null;
  logoSize?: number;
  wrap?: boolean;
}) {
  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,
        py: wrap ? 0.5 : 0,
      }}
    >
      <Box
        sx={{
          width: logoSize,
          height: logoSize,
          flexShrink: 0,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        {logoUrl ? (
          <AgencyLogo
            key={logoUrl}
            logoUrl={logoUrl}
            agency={agency}
            logoSize={logoSize}
          />
        ) : (
          <DashboardAssetIcon
            src={dashboardAssets.primaryAgencyAvatar}
            width={logoSize}
            height={logoSize}
            sx={{ flexShrink: 0 }}
          />
        )}
      </Box>

      {wrap ? (
        <Box
          sx={{
            color: isDark ? "#ffffff" : "#181d27",
            fontSize: 13,
            fontWeight: 400,
            minWidth: 0,
            flex: 1,
            whiteSpace: "normal",
            wordBreak: "break-word",
            lineHeight: 1.4,
            textAlign: "left",
          }}
        >
          {agency}
        </Box>
      ) : (
        <Typography
          noWrap
          sx={{
            color: isDark ? "#ffffff" : "#181d27",
            fontSize: 13,
            fontWeight: 400,
            minWidth: 0,
            flex: 1,
            textAlign: "left",
          }}
        >
          {agency}
        </Typography>
      )}
    </Box>
  );
}

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

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

        <Typography
          sx={{
            color: theme.palette.text.primary,
            fontSize: 13,
            lineHeight: showFullLabel ? 1.35 : 1.5,
            minWidth: 0,
            overflow: showFullLabel ? "visible" : "hidden",
            textOverflow: showFullLabel ? "clip" : "ellipsis",
            whiteSpace: showFullLabel ? "normal" : "nowrap",
            wordBreak: showFullLabel ? "break-word" : "normal",
          }}
        >
          {shortLabel}
        </Typography>
      </DocumentLink>
    </Box>
  );
}

function ViewDetailIcon({ size = 24 }: { size?: number }) {
  return (
    <Box
      component="svg"
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      sx={{ flexShrink: 0 }}
    >
      <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 { ViewDetailIcon };

export function ViewDetailAction({
  label,
  language = "km",
  onClick,
}: {
  label: string;
  language?: CdcGpsfMeetingRequestUiLang;
  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: getCdcGpsfMeetingRequestFont(language),
        }}
      >
        {label}
      </Typography>
    </ButtonBase>
  );
}
