"use client";

import React, { type ReactNode } from "react";
import { Box, Stack, TextField, Typography } from "@mui/material";
import type { Theme } from "@mui/material/styles";
import type { SxProps } from "@mui/material/styles";
import type { TextFieldProps } from "@mui/material/TextField";

export const REPLENISHMENT_FIELD_LABEL_SX = (theme: Theme) => ({
  color:
    theme.palette.mode === "dark"
      ? theme.palette.grey[100]
      : theme.palette.common.black,
  fontWeight: 700,
});

export const REPLENISHMENT_FIELD_ICON_SX = (theme: Theme) => ({
  color:
    theme.palette.mode === "dark"
      ? theme.palette.grey[100]
      : theme.palette.common.black,
});

export const REPLENISHMENT_TEXTFIELD_SX = (theme: Theme) =>
  ({
    "& .MuiFilledInput-root": {
      alignItems: "center",
      borderRadius: 2,
      bgcolor: theme.palette.mode === "dark" ? "grey.800" : "common.white",
      border: `1px solid ${theme.palette.divider}`,
      ...REPLENISHMENT_FIELD_CONTROL_ROOT_SX,
    },
    "& .MuiFilledInput-root.Mui-focused": {
      bgcolor: theme.palette.mode === "dark" ? "grey.800" : "common.white",
    },
    "& .MuiFilledInput-input": {
      paddingTop: REPLENISHMENT_FIELD_BODY_PY,
      paddingBottom: REPLENISHMENT_FIELD_BODY_PY,
    },
    "& .MuiFilledInput-input::placeholder, & .MuiInputBase-input::placeholder": {
      color: theme.palette.text.secondary,
      fontWeight: 400,
      opacity: 1,
    },
    "& .MuiFilledInput-root.Mui-focused .MuiFilledInput-input::placeholder, & .MuiFilledInput-root.Mui-focused .MuiInputBase-input::placeholder":
      {
        opacity: 0,
      },
  }) as const;

/** Autocomplete filled input — override theme default padding to match {@link REPLENISHMENT_TEXTFIELD_SX}. */
export const REPLENISHMENT_AUTOCOMPLETE_SX = (theme: Theme) =>
  ({
    width: "100%",
    ...REPLENISHMENT_TEXTFIELD_SX(theme),
    "& .MuiFormControl-root": {
      width: "100%",
    },
    "& .MuiAutocomplete-inputRoot": {
      ...REPLENISHMENT_FIELD_CONTROL_ROOT_SX,
      paddingTop: `${REPLENISHMENT_FIELD_BODY_PY} !important`,
      paddingBottom: `${REPLENISHMENT_FIELD_BODY_PY} !important`,
      paddingLeft: `${theme.spacing(REPLENISHMENT_FIELD_BODY_PX)} !important`,
      paddingRight: `${theme.spacing(3)} !important`,
    },
    "& .MuiAutocomplete-input": {
      padding: "0 !important",
    },
    "& .MuiAutocomplete-endAdornment": {
      right: theme.spacing(1),
    },
  }) as const;

/** Vertical padding inside replenishment filled inputs (see REPLENISHMENT_TEXTFIELD_SX). */
export const REPLENISHMENT_FIELD_BODY_PY = "12px";

/** Horizontal padding aligned with MUI filled input (spacing 1.5 = 12px). */
export const REPLENISHMENT_FIELD_BODY_PX = 1.5;

/** Fixed height for replenishment inputs, selects, and read-only value boxes. */
export const REPLENISHMENT_FIELD_CONTROL_HEIGHT = 44;

export const REPLENISHMENT_FIELD_CONTROL_ROOT_SX = {
  height: REPLENISHMENT_FIELD_CONTROL_HEIGHT,
  minHeight: REPLENISHMENT_FIELD_CONTROL_HEIGHT,
  maxHeight: REPLENISHMENT_FIELD_CONTROL_HEIGHT,
  boxSizing: "border-box" as const,
};

/** Read-only value box — same outer height as {@link ReplenishmentTextField}. */
export const REPLENISHMENT_READONLY_VALUE_SX = (theme: Theme) =>
  ({
    ...REPLENISHMENT_FIELD_CONTROL_ROOT_SX,
    borderRadius: 2,
    border: `1px solid ${theme.palette.divider}`,
    bgcolor: theme.palette.mode === "dark" ? "grey.800" : "common.white",
    px: REPLENISHMENT_FIELD_BODY_PX,
    display: "flex",
    alignItems: "center",
    minWidth: 0,
    overflow: "hidden",
  }) as const;

export function ReplenishmentReadonlyValue({
  children,
  fontWeight,
}: {
  children: React.ReactNode;
  fontWeight?: number;
}) {
  return (
    <Box sx={REPLENISHMENT_READONLY_VALUE_SX}>
      <Typography
        variant="body2"
        component="div"
        fontWeight={fontWeight}
        sx={{
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
          width: "100%",
          minWidth: 0,
          lineHeight: 1.43,
        }}
      >
        {children ?? "\u00A0"}
      </Typography>
    </Box>
  );
}

/** Invisible label spacer so action buttons align with labelled fields. */
export function ReplenishmentFieldLabelSpacer() {
  return (
    <Typography
      variant="body2"
      aria-hidden
      sx={{
        visibility: "hidden",
        lineHeight: 1.35,
        userSelect: "none",
      }}
    >
      {"\u00A0"}
    </Typography>
  );
}

/** Source DO summary header: same inset as textbox content area. */
export const REPLENISHMENT_SOURCE_HEADER_SX = (theme: Theme) =>
  ({
    bgcolor: "action.hover",
    borderRadius: 2,
    px: REPLENISHMENT_FIELD_BODY_PX,
    py: REPLENISHMENT_FIELD_BODY_PY,
    display: "flex",
    alignItems: "center",
    boxSizing: "border-box",
    border: `1px solid ${theme.palette.divider}`,
  }) as const;

type ReplenishmentFieldLabelProps = {
  icon?: ReactNode;
  title: string;
  required?: boolean;
  sx?: SxProps<Theme>;
};

export function ReplenishmentFieldLabel({
  icon,
  title,
  required = false,
  sx,
}: ReplenishmentFieldLabelProps) {
  return (
    <Stack direction="row" spacing={icon ? 1 : 0} alignItems="center" sx={sx}>
      {icon ?? null}
      <Typography
        variant="body2"
        sx={(theme) => ({
          ...REPLENISHMENT_FIELD_LABEL_SX(theme),
          whiteSpace: "normal",
          lineHeight: 1.35,
        })}
        component="span"
      >
        {title}
        {required ? (
          <Box component="span" color="error.main" aria-hidden="true">
            {" *"}
          </Box>
        ) : null}
      </Typography>
    </Stack>
  );
}

type ReplenishmentFilterFieldProps = ReplenishmentFieldLabelProps & {
  children: ReactNode;
};

export function ReplenishmentFilterField({
  icon,
  title,
  children,
  required = false,
}: ReplenishmentFilterFieldProps) {
  return (
    <Stack spacing={1} sx={{ flex: 1, minWidth: 0 }}>
      <ReplenishmentFieldLabel icon={icon} title={title} required={required} />
      {children}
    </Stack>
  );
}

type ReplenishmentTextFieldProps = Omit<TextFieldProps, "variant" | "size">;

export function ReplenishmentTextField(props: ReplenishmentTextFieldProps) {
  const { sx, InputProps, ...rest } = props;
  return (
    <TextField
      size="small"
      fullWidth
      variant="filled"
      sx={[REPLENISHMENT_TEXTFIELD_SX, sx] as SxProps<Theme>}
      InputProps={{ disableUnderline: true, ...InputProps }}
      {...rest}
    />
  );
}

/** Filled select matching {@link ReplenishmentTextField} border and padding. */
export const REPLENISHMENT_FILLED_SELECT_SX = (theme: Theme) =>
  ({
    ...REPLENISHMENT_TEXTFIELD_SX(theme),
    "& .MuiFilledInput-root": {
      alignItems: "center",
      borderRadius: 2,
      bgcolor: theme.palette.mode === "dark" ? "grey.800" : "common.white",
      border: `1px solid ${theme.palette.divider}`,
      "&::before, &::after": { display: "none" },
      ...REPLENISHMENT_FIELD_CONTROL_ROOT_SX,
    },
    "& .MuiSelect-select": {
      paddingTop: REPLENISHMENT_FIELD_BODY_PY,
      paddingBottom: REPLENISHMENT_FIELD_BODY_PY,
      display: "flex",
      alignItems: "center",
    },
  }) as const;

/** Read-only item row value — blank until a line is selected. */
export function ReplenishmentItemEntryPlainText({
  value,
  reserveSpace = false,
  sx,
}: {
  value: string;
  /** Keep column width/height when empty (e.g. original shipment qty). */
  reserveSpace?: boolean;
  sx?: SxProps<Theme>;
}) {
  const isEmpty = value.trim() === "";
  if (isEmpty && !reserveSpace) return null;

  return (
    <Box
      component="span"
      sx={
        [
          (theme) => ({
            display: "block",
            color: theme.palette.text.primary,
            wordBreak: "break-word",
            minWidth: 0,
            minHeight: reserveSpace ? theme.spacing(5) : undefined,
          }),
          sx,
        ] as SxProps<Theme>
      }
    >
      {isEmpty ? "\u00A0" : value}
    </Box>
  );
}

type ReplenishmentQtyWithUomFieldProps = {
  placeholder?: string;
  value: string;
  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  uom?: string;
  sx?: SxProps<Theme>;
  inputProps?: React.InputHTMLAttributes<HTMLInputElement>;
};

/** Replenish qty textbox (search-field style) with uom label attached on the right outside. */
export function ReplenishmentQtyWithUomField({
  placeholder,
  value,
  onChange,
  uom = "",
  sx,
  inputProps,
}: ReplenishmentQtyWithUomFieldProps) {
  return (
    <Stack
      direction="row"
      alignItems="center"
      spacing={0.75}
      sx={{ flexShrink: 0, ...(typeof sx === "function" ? undefined : sx) }}
    >
      <ReplenishmentTextField
        type="number"
        hiddenLabel
        placeholder={placeholder ?? ""}
        value={value}
        onChange={onChange}
        inputProps={inputProps}
        sx={{ width: 100 }}
      />
      <Box component="span" sx={REPLENISHMENT_TABLE_UOM_SLOT_SX}>
        {uom || "\u00A0"}
      </Box>
    </Stack>
  );
}

/** Tracking dialog table — horizontal scroll, no fixed layout (avoids column text stacking). */
export const REPLENISHMENT_TRACKING_TABLE_SX = {
  width: "max-content",
  minWidth: "100%",
  "& .MuiTableCell-root": {
    typography: "body2",
    borderColor: "divider",
    py: 1,
    px: 1.25,
    whiteSpace: "nowrap",
  },
  "& .MuiTableCell-root:first-of-type": {
    pl: 1.5,
  },
  "& .MuiTableHead-root .MuiTableCell-root": {
    fontWeight: 600,
    color: "text.secondary",
    bgcolor: "action.hover",
    borderBottom: "1px solid",
    borderColor: "divider",
  },
  "& .MuiTableBody-root .MuiTableRow-root:not(:last-of-type) .MuiTableCell-root": {
    borderBottom: "1px solid",
    borderColor: "divider",
  },
} as const;

export const REPLENISHMENT_TRACKING_CELL_ELLIPSIS_SX = {
  maxWidth: 160,
  overflow: "hidden",
  textOverflow: "ellipsis",
} as const;

export const REPLENISHMENT_TRACKING_CELL_WRAP_SX = {
  minWidth: 120,
  maxWidth: 200,
  whiteSpace: "normal",
  wordBreak: "break-word",
} as const;

export const REPLENISHMENT_TABLE_SX = {
  width: "100%",
  tableLayout: "fixed",
  "& .MuiTableCell-root": {
    typography: "body2",
    borderColor: "divider",
    py: 1,
    px: 1.25,
  },
  "& .MuiTableCell-root:first-of-type": {
    pl: 1.5,
  },
  "& .MuiTableHead-root .MuiTableCell-root": {
    fontWeight: 600,
    color: "text.secondary",
    bgcolor: "action.hover",
    borderBottom: "1px solid",
    borderColor: "divider",
  },
  "& .MuiTableBody-root .MuiTableRow-root:not(:last-of-type) .MuiTableCell-root": {
    borderBottom: "1px solid",
    borderColor: "divider",
  },
} as const;

export const REPLENISHMENT_TABLE_HEAD_CELL_SX = {
  typography: "body2",
  fontWeight: 600,
} as const;

export const REPLENISHMENT_TABLE_BODY_CELL_SX = {
  typography: "body2",
  verticalAlign: "middle",
} as const;

/** Extra inset for the first column (item code). */
export const REPLENISHMENT_TABLE_FIRST_CELL_SX = {
  pl: 3,
} as const;

/** Entry row: no bottom border on last row. */
export const REPLENISHMENT_TABLE_ENTRY_ROW_SX = {
  "& .MuiTableCell-root": {
    borderBottom: 0,
  },
} as const;

/** In-table inputs — always show filled border; compact padding for row alignment. */
export const REPLENISHMENT_TABLE_INLINE_TEXTFIELD_SX = (theme: Theme) =>
  ({
    ...REPLENISHMENT_TEXTFIELD_SX(theme),
    "& .MuiFilledInput-root": {
      alignItems: "center",
      borderRadius: 1.5,
      bgcolor: theme.palette.mode === "dark" ? "grey.800" : "common.white",
      border: `1px solid ${theme.palette.divider}`,
      "&:hover": {
        bgcolor: theme.palette.mode === "dark" ? "grey.800" : "common.white",
      },
      "&.Mui-focused": {
        bgcolor: theme.palette.mode === "dark" ? "grey.800" : "common.white",
        borderColor: theme.palette.primary.main,
      },
    },
    "& .MuiFilledInput-input": {
      paddingTop: "6px",
      paddingBottom: "6px",
      paddingLeft: 0,
      paddingRight: 0,
    },
    "& input[type=number]": {
      MozAppearance: "textfield",
    },
    "& input[type=number]::-webkit-outer-spin-button, & input[type=number]::-webkit-inner-spin-button":
      {
        WebkitAppearance: "none",
        margin: 0,
      },
  }) as const;

/** Table autocomplete — same inset as plain text in first column. */
export const REPLENISHMENT_TABLE_AUTOCOMPLETE_SX = (theme: Theme) =>
  ({
    width: "100%",
    ...REPLENISHMENT_TABLE_INLINE_TEXTFIELD_SX(theme),
    "& .MuiFormControl-root": {
      width: "100%",
    },
    "& .MuiAutocomplete-inputRoot": {
      paddingTop: "6px !important",
      paddingBottom: "6px !important",
      paddingLeft: `${theme.spacing(1)} !important`,
      paddingRight: "56px !important",
      bgcolor: `${theme.palette.mode === "dark" ? theme.palette.grey[800] : theme.palette.common.white} !important`,
      border: `1px solid ${theme.palette.divider} !important`,
      borderRadius: `${theme.shape.borderRadius * 1.5}px !important`,
      "&.Mui-focused": {
        borderColor: `${theme.palette.primary.main} !important`,
      },
    },
    "& .MuiAutocomplete-input": {
      padding: "0 !important",
      minWidth: 48,
    },
    "& .MuiAutocomplete-endAdornment": {
      right: theme.spacing(0.75),
      gap: theme.spacing(0.25),
      "& .MuiAutocomplete-clearIndicator": {
        visibility: "visible",
      },
    },
  }) as const;

/** Right-aligned qty + uom slot shared by data rows and entry row. */
export const REPLENISHMENT_TABLE_QTY_CELL_INNER_SX = {
  display: "flex",
  justifyContent: "flex-end",
  alignItems: "center",
  width: "100%",
  gap: 0.75,
} as const;

export const REPLENISHMENT_TABLE_UOM_SLOT_SX = {
  minWidth: 28,
  whiteSpace: "nowrap",
  display: "inline-block",
  flexShrink: 0,
} as const;

export const REPLENISHMENT_TABLE_ACTION_CELL_INNER_SX = {
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
  width: "100%",
} as const;

/** In-table select — compact padding; truncate long selected labels. */
export const REPLENISHMENT_TABLE_INLINE_SELECT_SX = (theme: Theme) =>
  ({
    ...REPLENISHMENT_FILLED_SELECT_SX(theme),
    "& .MuiSelect-select": {
      paddingTop: "6px",
      paddingBottom: "6px",
      paddingLeft: theme.spacing(1),
      paddingRight: `${theme.spacing(3)} !important`,
      overflow: "hidden",
      textOverflow: "ellipsis",
      whiteSpace: "nowrap",
    },
  }) as const;

export const replenishmentSearchGridLabelSx = (col: number) => ({
  gridColumn: { xs: 1, lg: col },
  gridRow: { xs: "auto", lg: 1 },
  minWidth: "min-content",
  overflow: "hidden",
  textOverflow: "ellipsis",
});

export const replenishmentSearchGridInputSx = (col: number) => ({
  gridColumn: { xs: 1, lg: col },
  gridRow: { xs: "auto", lg: 2 },
  minWidth: 0,
  display: "flex",
  alignItems: "stretch",
  "& .MuiFormControl-root": {
    width: "100%",
  },
});

/** Lookup / tracking buttons beside the three filter inputs (4th grid column on lg). */
export const replenishmentSearchGridActionsSx = {
  gridColumn: { xs: 1, lg: 4 },
  gridRow: { xs: "auto", lg: 2 },
  display: "flex",
  justifyContent: { xs: "stretch", lg: "flex-start" },
  alignItems: "stretch",
  flexWrap: { xs: "wrap", lg: "nowrap" },
  gap: 1.5,
  minWidth: 0,
  "& .MuiButton-root": {
    flex: { xs: 1, lg: "0 0 auto" },
    alignSelf: "stretch",
  },
};

/** Match {@link ReplenishmentFieldLabel} typography on field-height buttons. */
export const REPLENISHMENT_LOOKUP_BUTTON_TEXT_SX = (theme: Theme) => ({
  fontSize: theme.typography.body2.fontSize,
  fontWeight: 600,
  lineHeight: 1,
});

/** Base button style — same 44px height as {@link ReplenishmentTextField}. */
export const REPLENISHMENT_FIELD_BUTTON_SX = (theme: Theme) =>
  ({
    ...REPLENISHMENT_LOOKUP_BUTTON_TEXT_SX(theme),
    ...REPLENISHMENT_FIELD_CONTROL_ROOT_SX,
    paddingTop: 0,
    paddingBottom: 0,
    px: REPLENISHMENT_FIELD_BODY_PX,
    borderRadius: 2,
    boxShadow: "none",
    textTransform: "none",
    whiteSpace: "nowrap",
    flexShrink: 0,
    "&.MuiButton-root": {
      ...REPLENISHMENT_FIELD_CONTROL_ROOT_SX,
    },
    "& .MuiButton-startIcon": {
      margin: 0,
      marginRight: theme.spacing(0.75),
      "& > *:nth-of-type(1)": {
        fontSize: 18,
      },
    },
  }) as const;

export const REPLENISHMENT_LOOKUP_BUTTON_SX = (theme: Theme) =>
  ({
    ...REPLENISHMENT_FIELD_BUTTON_SX(theme),
    alignSelf: "stretch",
    px: REPLENISHMENT_FIELD_BODY_PX,
    minWidth: { xs: "auto", lg: 108 },
  }) as const;

/** Outlined companion button (e.g. replenishment tracking) beside lookup. */
export const REPLENISHMENT_OUTLINED_ACTION_BUTTON_SX = (theme: Theme) =>
  ({
    ...REPLENISHMENT_FIELD_BUTTON_SX(theme),
    minWidth: "auto",
    px: REPLENISHMENT_FIELD_BODY_PX,
    borderColor: theme.palette.divider,
    color: theme.palette.text.primary,
    bgcolor: theme.palette.mode === "dark" ? "grey.800" : "common.white",
    "&:hover": {
      borderColor: theme.palette.primary.main,
      bgcolor: theme.palette.mode === "dark" ? "grey.700" : "grey.50",
    },
  }) as const;

