"use client";

import CalendarTodayIcon from "@mui/icons-material/CalendarToday";
import LocalShippingIcon from "@mui/icons-material/LocalShipping";
import PlaylistAddCheckCircleIcon from "@mui/icons-material/PlaylistAddCheckCircle";
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
import ClearIcon from "@mui/icons-material/Clear";
import StorefrontIcon from "@mui/icons-material/Storefront";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import IconButton from "@mui/material/IconButton";
import MenuItem from "@mui/material/MenuItem";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { useMediaQuery, useTheme } from "@mui/material";
import type { Theme } from "@mui/material/styles";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import dayjs from "dayjs";
import type { ReactNode } from "react";
import {
  PO_WORKBENCH_ESCALATION_FILTER_OPTIONS,
  PO_WORKBENCH_RECEIVE_STATUS_OPTIONS,
  type ReceiveStatusFilter,
  type ReportStatusFilter,
} from "@/components/PoWorkbench/types";
import { trimString } from "@/components/PoWorkbench/workbenchUtils";
import { useTranslation } from "react-i18next";

/** Panel heading — black in light mode for strong contrast. */
const panelTitleSx = (theme: Theme) => ({
  color:
    theme.palette.mode === "dark"
      ? theme.palette.grey[100]
      : theme.palette.common.black,
  fontWeight: 700,
  letterSpacing: 0.15,
});

/** Field labels — same black / light contrast as panel title; lighter weight keeps hierarchy. */
const fieldLabelSx = (theme: Theme) => ({
  color:
    theme.palette.mode === "dark"
      ? theme.palette.grey[100]
      : theme.palette.common.black,
  fontWeight: 600,
});

/** Select menu opens upward from the field (anchor top of input, list grows up). */
const ADVANCED_SELECT_MENU_PROPS = {
  anchorOrigin: { vertical: "top" as const, horizontal: "left" as const },
  transformOrigin: { vertical: "bottom" as const, horizontal: "left" as const },
};

/** Black in light mode; light icon in dark mode for contrast. */
const sectionIconSx = (theme: Theme) => ({
  color:
    theme.palette.mode === "dark"
      ? theme.palette.grey[100]
      : theme.palette.common.black,
});

const ADVANCED_TEXTFIELD_SX = (theme: Theme) =>
  ({
    "& .MuiFilledInput-root": {
      alignItems: "center",
    },
    "& .MuiFilledInput-input": {
      paddingTop: "10px",
      paddingBottom: "10px",
    },
    "& .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,
      },
    "& .MuiSelect-select": {
      display: "flex",
      alignItems: "center",
    },
  }) as const;

function ymdToDayjsOrNull(value: unknown) {
  const v = trimString(value);
  if (!v) return null;
  const d = dayjs(v, "YYYY-MM-DD", true);
  return d.isValid() ? d : null;
}

interface FilterSectionProps {
  icon: ReactNode;
  title: string;
  children: ReactNode;
  /** When true and `onClear` is set, show a clear icon to the right of the title. */
  clearVisible?: boolean;
  onClear?: () => void;
  clearLabel?: string;
}

function FilterSection({
  icon,
  title,
  children,
  clearVisible,
  onClear,
  clearLabel,
}: FilterSectionProps) {
  const showClear = Boolean(clearVisible && onClear);
  const clearSlot = Boolean(onClear);

  return (
    <Stack spacing={1}>
      <Stack
        direction="row"
        spacing={1}
        alignItems="center"
        sx={{ minWidth: 0 }}
      >
        {icon}
        <Typography
          variant="body2"
          sx={(theme) => ({
            ...fieldLabelSx(theme),
            flex: 1,
            minWidth: 0,
          })}
        >
          {title}
        </Typography>
        {clearSlot ? (
          <IconButton
            size="small"
            onClick={showClear ? onClear : undefined}
            aria-label={clearLabel}
            aria-hidden={!showClear}
            tabIndex={showClear ? 0 : -1}
            sx={{
              flexShrink: 0,
              color: "text.secondary",
              visibility: showClear ? "visible" : "hidden",
              pointerEvents: showClear ? "auto" : "none",
            }}
          >
            <ClearIcon fontSize="small" />
          </IconButton>
        ) : null}
      </Stack>
      {children}
    </Stack>
  );
}

interface DateRangeFieldProps {
  title: string;
  icon: ReactNode;
  isNarrowLayout: boolean;
  fromValue: string;
  toValue: string;
  onFromChange: (next: string) => void;
  onToChange: (next: string) => void;
  clearLabel: string;
}

function DateRangeField({
  title,
  icon,
  isNarrowLayout,
  fromValue,
  toValue,
  onFromChange,
  onToChange,
  clearLabel,
}: DateRangeFieldProps) {
  const { t } = useTranslation("poWorkbench");
  const datePh = t("advanced.datePlaceholder");
  const hasRange = Boolean(trimString(fromValue) || trimString(toValue));

  return (
    <FilterSection
      icon={icon}
      title={title}
      clearVisible={hasRange}
      onClear={() => {
        onFromChange("");
        onToChange("");
      }}
      clearLabel={clearLabel}
    >
      <Stack
        direction={isNarrowLayout ? "column" : "row"}
        spacing={isNarrowLayout ? 0.75 : 1}
        alignItems={isNarrowLayout ? "stretch" : "center"}
        sx={{ minWidth: 0 }}
      >
        <LocalizationProvider dateAdapter={AdapterDayjs}>
          <DatePicker
            format="YYYY-MM-DD"
            value={ymdToDayjsOrNull(fromValue)}
            onChange={(v) => onFromChange(v ? v.format("YYYY-MM-DD") : "")}
            slotProps={{
              textField: {
                size: "small",
                fullWidth: true,
                variant: "filled",
                placeholder: datePh,
                sx: ADVANCED_TEXTFIELD_SX,
                InputProps: { disableUnderline: true },
              },
            }}
          />
        </LocalizationProvider>
        <Typography
          variant="caption"
          color="text.secondary"
          sx={{
            flexShrink: 0,
            alignSelf: isNarrowLayout ? "flex-start" : "center",
            px: isNarrowLayout ? 0.25 : 0,
            py: isNarrowLayout ? 0.25 : 0,
          }}
        >
          {t("advanced.dateRangeTo")}
        </Typography>
        <LocalizationProvider dateAdapter={AdapterDayjs}>
          <DatePicker
            format="YYYY-MM-DD"
            value={ymdToDayjsOrNull(toValue)}
            onChange={(v) => onToChange(v ? v.format("YYYY-MM-DD") : "")}
            slotProps={{
              textField: {
                size: "small",
                fullWidth: true,
                variant: "filled",
                placeholder: datePh,
                sx: ADVANCED_TEXTFIELD_SX,
                InputProps: { disableUnderline: true },
              },
            }}
          />
        </LocalizationProvider>
      </Stack>
    </FilterSection>
  );
}

export interface PoWorkbenchAdvancedSearchPanelProps {
  supplierQuery: string;
  orderDateFrom: string;
  orderDateTo: string;
  etaDateFrom: string;
  etaDateTo: string;
  reportStatus: ReportStatusFilter;
  receiveStatus: ReceiveStatusFilter;
  onSupplierQueryChange: (next: string) => void;
  onOrderDateFromChange: (next: string) => void;
  onOrderDateToChange: (next: string) => void;
  onEtaDateFromChange: (next: string) => void;
  onEtaDateToChange: (next: string) => void;
  onReportStatusChange: (next: ReportStatusFilter) => void;
  onReceiveStatusChange: (next: ReceiveStatusFilter) => void;
  onApply: () => void;
  onReset: () => void;
}

export default function PoWorkbenchAdvancedSearchPanel({
  supplierQuery,
  orderDateFrom,
  orderDateTo,
  etaDateFrom,
  etaDateTo,
  reportStatus,
  receiveStatus,
  onSupplierQueryChange,
  onOrderDateFromChange,
  onOrderDateToChange,
  onEtaDateFromChange,
  onEtaDateToChange,
  onReportStatusChange,
  onReceiveStatusChange,
  onApply,
  onReset,
}: PoWorkbenchAdvancedSearchPanelProps) {
  const theme = useTheme();
  /** Layout concern: narrow width stacks fields vertically. */
  const shouldStackFields = useMediaQuery(theme.breakpoints.down("lg"), {
    noSsr: true,
  });
  /** Density concern: short viewport reduces vertical spacing and button heights. */
  const isShortPanelHeight = useMediaQuery("(max-height: 820px)", {
    noSsr: true,
  });
  const shouldUseCompactDensity = shouldStackFields || isShortPanelHeight;
  const { t } = useTranslation("poWorkbench");
  const { t: tPo } = useTranslation("purchaseOrder");

  return (
    <Box
      sx={{
        position: "absolute",
        inset: 0,
        display: "flex",
        flexDirection: "column",
        overflow: "hidden",
        bgcolor: (theme) =>
          theme.palette.mode === "dark" ? "grey.900" : "grey.50",
      }}
    >
      <Stack
        spacing={shouldUseCompactDensity ? 0.75 : 1}
        sx={{
          px: 1.5,
          pt: shouldUseCompactDensity ? 0.75 : 1,
          pb: shouldUseCompactDensity ? 0.75 : 1.25,
          overflowY: "auto",
          overflowX: "hidden",
          scrollbarGutter: "stable",
          flex: 1,
          minHeight: 0,
        }}
      >
        <Typography component="h2" variant="subtitle1" sx={panelTitleSx}>
          {t("advanced.title")}
        </Typography>

        <FilterSection
          icon={<StorefrontIcon fontSize="small" sx={sectionIconSx} />}
          title={t("advanced.supplier")}
          clearVisible={trimString(supplierQuery) !== ""}
          onClear={() => onSupplierQueryChange("")}
          clearLabel={t("advanced.clearCriterion")}
        >
          <TextField
            size="small"
            fullWidth
            variant="filled"
            value={supplierQuery}
            onChange={(e) => onSupplierQueryChange(e.target.value)}
            placeholder={t("advanced.supplierPlaceholder")}
            sx={ADVANCED_TEXTFIELD_SX}
            InputProps={{ disableUnderline: true }}
          />
        </FilterSection>

        <DateRangeField
          title={t("advanced.orderDate")}
          icon={<CalendarTodayIcon fontSize="small" sx={sectionIconSx} />}
          isNarrowLayout={shouldStackFields}
          fromValue={orderDateFrom}
          toValue={orderDateTo}
          onFromChange={onOrderDateFromChange}
          onToChange={onOrderDateToChange}
          clearLabel={t("advanced.clearCriterion")}
        />

        <DateRangeField
          title={t("advanced.eta")}
          icon={<LocalShippingIcon fontSize="small" sx={sectionIconSx} />}
          isNarrowLayout={shouldStackFields}
          fromValue={etaDateFrom}
          toValue={etaDateTo}
          onFromChange={onEtaDateFromChange}
          onToChange={onEtaDateToChange}
          clearLabel={t("advanced.clearCriterion")}
        />

        <Stack
          direction={shouldStackFields ? "column" : "row"}
          spacing={shouldUseCompactDensity ? 0.75 : shouldStackFields ? 1 : 2}
          sx={{ alignItems: "stretch" }}
        >
          <Box sx={{ flex: 1, minWidth: 0 }}>
            <FilterSection
              icon={
                <PlaylistAddCheckCircleIcon
                  fontSize="small"
                  sx={sectionIconSx}
                />
              }
              title={t("advanced.reportStatus")}
              clearVisible={reportStatus !== "ALL"}
              onClear={() => onReportStatusChange("ALL")}
              clearLabel={t("advanced.clearCriterion")}
            >
              <TextField
                size="small"
                fullWidth
                variant="filled"
                select
                value={reportStatus}
                onChange={(e) =>
                  onReportStatusChange(e.target.value as ReportStatusFilter)
                }
                sx={ADVANCED_TEXTFIELD_SX}
                InputProps={{ disableUnderline: true }}
                SelectProps={{ MenuProps: ADVANCED_SELECT_MENU_PROPS }}
              >
                <MenuItem value="ALL">{t("advanced.all")}</MenuItem>
                {PO_WORKBENCH_ESCALATION_FILTER_OPTIONS.map((opt) => (
                  <MenuItem key={opt.value} value={opt.value}>
                    {tPo(opt.labelKey)}
                  </MenuItem>
                ))}
              </TextField>
            </FilterSection>
          </Box>
          <Box sx={{ flex: 1, minWidth: 0 }}>
            <FilterSection
              icon={<ReceiptLongIcon fontSize="small" sx={sectionIconSx} />}
              title={t("advanced.receiveStatus")}
              clearVisible={receiveStatus !== "ALL"}
              onClear={() => onReceiveStatusChange("ALL")}
              clearLabel={t("advanced.clearCriterion")}
            >
              <TextField
                size="small"
                fullWidth
                variant="filled"
                select
                value={receiveStatus}
                onChange={(e) =>
                  onReceiveStatusChange(e.target.value as ReceiveStatusFilter)
                }
                sx={ADVANCED_TEXTFIELD_SX}
                InputProps={{ disableUnderline: true }}
                SelectProps={{ MenuProps: ADVANCED_SELECT_MENU_PROPS }}
              >
                <MenuItem value="ALL">{t("advanced.all")}</MenuItem>
                {PO_WORKBENCH_RECEIVE_STATUS_OPTIONS.map((opt) => (
                  <MenuItem key={opt.value} value={opt.value}>
                    {tPo(opt.labelKey)}
                  </MenuItem>
                ))}
              </TextField>
            </FilterSection>
          </Box>
        </Stack>
      </Stack>

      <Stack
        direction={shouldStackFields ? "column" : "row"}
        spacing={1}
        sx={{
          px: 1.5,
          pb: shouldUseCompactDensity ? 1 : 1.5,
          pt: shouldUseCompactDensity ? 0.75 : 1,
          borderTop: 1,
          borderColor: "divider",
          bgcolor: "background.paper",
        }}
      >
        <Button
          variant="contained"
          fullWidth
          size="large"
          onClick={onApply}
          sx={{ minHeight: shouldUseCompactDensity ? 46 : 52, fontWeight: 700 }}
        >
          {t("advanced.search")}
        </Button>
        <Button
          variant="outlined"
          fullWidth
          size="large"
          onClick={onReset}
          sx={{ minHeight: shouldUseCompactDensity ? 46 : 52, fontWeight: 700 }}
        >
          {t("advanced.reset")}
        </Button>
      </Stack>
    </Box>
  );
}
