"use client";

import React, { memo } from "react";
import {
  Box,
  Button,
  Chip,
  Paper,
  Stack,
  Typography,
} from "@mui/material";
import { alpha } from "@mui/material/styles";
import { ArrowRight, Clock, HelpCircle, Trash2, Undo2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import type {
  ScheduleModification,
  ScheduledDeleteSnapshot,
} from "@/components/Shop/scheduleDragWorkspace";

type Props = {
  modifications: ScheduleModification[];
  pendingDeletes: ScheduledDeleteSnapshot[];
  onRevert: (shopId: number, currentLaneId: string) => void;
  onRevertDelete: (truckRowId: number) => void;
  errorTruckRowIds?: Set<number>;
  validationErrorsByTruckRowId?: Map<number, string>;
};

const ScheduleReviewQueue: React.FC<Props> = ({
  modifications,
  pendingDeletes,
  onRevert,
  onRevertDelete,
  errorTruckRowIds = new Set(),
  validationErrorsByTruckRowId = new Map(),
}) => {
  const { t } = useTranslation("shop");
  const totalCount = modifications.length + pendingDeletes.length;
  const isEmpty = totalCount === 0;

  return (
    <Paper
      variant="outlined"
      sx={{
        display: "flex",
        flexDirection: "column",
        width: "100%",
        minWidth: "100%",
        minHeight: 0,
        height: "100%",
        overflow: "hidden",
        bgcolor: "grey.50",
        boxSizing: "border-box",
      }}
    >
      <Box
        sx={{
          px: 1.5,
          py: 1.25,
          borderBottom: 1,
          borderColor: "divider",
          bgcolor: "background.paper",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          flexShrink: 0,
        }}
      >
        <Stack direction="row" spacing={0.75} alignItems="center">
          <Clock size={16} color="#ed6c02" />
          <Typography variant="body2" sx={{ fontWeight: 800 }}>
            {t("schedule_review_queue")}
          </Typography>
        </Stack>
        <Chip
          size="small"
          label={t("schedule_review_count", { count: totalCount })}
          sx={{
            fontWeight: 800,
            bgcolor: alpha("#ed6c02", 0.12),
            color: "warning.dark",
          }}
        />
      </Box>

      <Box sx={{ flex: 1, overflow: "auto", p: 1.25 }}>
        {isEmpty ? (
          <Stack
            alignItems="center"
            justifyContent="center"
            sx={{ height: "100%", minHeight: 160, textAlign: "center", px: 2 }}
          >
            <HelpCircle size={32} color="#cbd5e1" strokeWidth={1.25} />
            <Typography variant="caption" sx={{ fontWeight: 800, mt: 1 }}>
              {t("schedule_review_empty")}
            </Typography>
            <Typography variant="caption" color="text.secondary" sx={{ mt: 0.5 }}>
              {t("schedule_review_empty_hint")}
            </Typography>
          </Stack>
        ) : (
          <Stack spacing={1} sx={{ width: "100%" }}>
            {pendingDeletes.map((del) => (
              <Paper
                key={`delete-${del.truckRowId}`}
                variant="outlined"
                sx={{
                  p: 1.25,
                  width: "100%",
                  boxSizing: "border-box",
                  borderColor: "error.light",
                  bgcolor: alpha("#d32f2f", 0.04),
                  "&:hover": {
                    borderColor: "error.main",
                    boxShadow: 1,
                  },
                }}
              >
                <Stack
                  direction="row"
                  justifyContent="space-between"
                  alignItems="flex-start"
                  spacing={1}
                >
                  <Box sx={{ minWidth: 0 }}>
                    <Stack direction="row" spacing={0.5} alignItems="center">
                      <Trash2 size={12} color="#d32f2f" />
                      <Typography variant="caption" sx={{ fontWeight: 800 }}>
                        {del.shopCode}
                      </Typography>
                    </Stack>
                    <Typography
                      variant="caption"
                      color="text.secondary"
                      display="block"
                      noWrap
                    >
                      {del.displayName}
                    </Typography>
                  </Box>
                  <Button
                    size="small"
                    onClick={() => onRevertDelete(del.truckRowId)}
                    startIcon={<Undo2 size={12} />}
                    sx={{
                      minWidth: 0,
                      px: 1,
                      py: 0.25,
                      fontSize: "0.65rem",
                      fontWeight: 700,
                      textTransform: "none",
                      flexShrink: 0,
                    }}
                  >
                    {t("schedule_review_revert")}
                  </Button>
                </Stack>

                <Box
                  sx={{
                    mt: 1,
                    p: 1,
                    borderRadius: 1,
                    bgcolor: "grey.50",
                    fontSize: "0.65rem",
                  }}
                >
                  <Stack direction="row" spacing={0.5} alignItems="center" flexWrap="wrap">
                    <Typography variant="caption" color="text.secondary">
                      {t("schedule_review_delete_action")}
                    </Typography>
                    <Typography variant="caption" sx={{ fontWeight: 700 }}>
                      {del.fromLaneLabel}
                    </Typography>
                  </Stack>
                  {del.location && (
                    <Typography
                      variant="caption"
                      color="text.secondary"
                      display="block"
                      sx={{ mt: 0.5 }}
                      noWrap
                    >
                      {del.location}
                    </Typography>
                  )}
                </Box>
              </Paper>
            ))}

            {modifications.map((mod) => {
              const hasError = errorTruckRowIds.has(mod.truckRowId);
              const errorMessage = validationErrorsByTruckRowId.get(mod.truckRowId);
              return (
                <Paper
                  key={mod.truckRowId}
                  variant="outlined"
                  sx={{
                    p: 1.25,
                    width: "100%",
                    boxSizing: "border-box",
                    borderColor: hasError ? "error.main" : "warning.light",
                    bgcolor: hasError ? "error.50" : "background.paper",
                    "&:hover": {
                      borderColor: "warning.main",
                      boxShadow: 1,
                    },
                  }}
                >
                  <Stack
                    direction="row"
                    justifyContent="space-between"
                    alignItems="flex-start"
                    spacing={1}
                  >
                    <Box sx={{ minWidth: 0 }}>
                      <Typography variant="caption" sx={{ fontWeight: 800 }}>
                        {mod.shopCode}
                      </Typography>
                      <Typography
                        variant="caption"
                        color="text.secondary"
                        display="block"
                        noWrap
                      >
                        {mod.displayName}
                      </Typography>
                    </Box>
                    <Button
                      size="small"
                      onClick={() => onRevert(mod.truckRowId, mod.toLaneId)}
                      startIcon={<Undo2 size={12} />}
                      sx={{
                        minWidth: 0,
                        px: 1,
                        py: 0.25,
                        fontSize: "0.65rem",
                        fontWeight: 700,
                        textTransform: "none",
                        flexShrink: 0,
                      }}
                    >
                      {t("schedule_review_revert")}
                    </Button>
                  </Stack>

                  <Box
                    sx={{
                      mt: 1,
                      p: 1,
                      borderRadius: 1,
                      bgcolor: "grey.50",
                      fontSize: "0.65rem",
                    }}
                  >
                    {hasError && errorMessage && (
                      <Typography
                        variant="caption"
                        color="error"
                        display="block"
                        sx={{ fontWeight: 700, mb: 0.5 }}
                      >
                        {errorMessage}
                      </Typography>
                    )}
                    {mod.isLaneChanged && (
                      <Stack
                        direction="row"
                        spacing={0.5}
                        alignItems="center"
                        flexWrap="wrap"
                        sx={{ mb: 0.5 }}
                      >
                        <Typography variant="caption" color="text.secondary">
                          {t("schedule_review_lane_change")}
                        </Typography>
                        <Typography variant="caption" sx={{ fontWeight: 700 }}>
                          {mod.fromLaneLabel}
                        </Typography>
                        <ArrowRight size={10} />
                        <Typography
                          variant="caption"
                          sx={{ fontWeight: 800, color: "primary.main" }}
                        >
                          {mod.toLaneLabel}
                        </Typography>
                      </Stack>
                    )}
                    {mod.isDistrictChanged && (
                      <Stack
                        direction="row"
                        spacing={0.5}
                        alignItems="center"
                        flexWrap="wrap"
                        sx={{ mb: 0.5 }}
                      >
                        <Typography variant="caption" color="text.secondary">
                          {t("schedule_review_district_change")}
                        </Typography>
                        <Typography variant="caption" sx={{ fontWeight: 700 }}>
                          {mod.oldDistrictLabel}
                        </Typography>
                        <ArrowRight size={10} />
                        <Typography
                          variant="caption"
                          sx={{ fontWeight: 800, color: "primary.main" }}
                        >
                          {mod.newDistrictLabel}
                        </Typography>
                      </Stack>
                    )}
                    <Stack direction="row" spacing={0.5} alignItems="center" flexWrap="wrap">
                      <Typography variant="caption" color="text.secondary">
                        {t("schedule_review_seq")}
                      </Typography>
                      {mod.isSeqChanged ? (
                        <>
                          <Typography
                            variant="caption"
                            sx={{ textDecoration: "line-through", color: "text.secondary" }}
                          >
                            {mod.oldLoadingSequence}
                          </Typography>
                          <ArrowRight size={10} />
                          <Typography
                            variant="caption"
                            sx={{ fontWeight: 800, color: "success.dark" }}
                          >
                            {mod.newLoadingSequence}
                          </Typography>
                        </>
                      ) : (
                        <Typography variant="caption" sx={{ fontWeight: 600 }}>
                          {mod.newLoadingSequence}
                        </Typography>
                      )}
                    </Stack>
                  </Box>
                </Paper>
              );
            })}
          </Stack>
        )}
      </Box>
    </Paper>
  );
};

export default memo(ScheduleReviewQueue);
