import React, { useState } from "react";
import {
  Box,
  Paper,
  Typography,
  Button,
  TextField,
  InputAdornment,
  IconButton,
  Chip,
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
  FormControl,
  InputLabel,
  Select,
  Grid,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  SpeedDial,
  SpeedDialAction,
  SpeedDialIcon,
} from "@mui/material";
import {
  Search as SearchIcon,
  Clear as ClearIcon,
  MoreVert as MoreVertIcon,
  Visibility as ViewIcon,
  Check as ConfirmIcon,
  Close as CancelIcon,
  Delete as DeleteIcon,
  Add as AddIcon,
  Download as DownloadIcon,
  Upload as UploadIcon,
  SwapHoriz as TransferIcon,
  Build as AdjustmentIcon,
  FilterList as FilterIcon,
} from "@mui/icons-material";
import { useTranslation, Trans } from "react-i18next";
import { DataGrid, GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { Dayjs } from "dayjs";
import "dayjs/locale/it";
import {
  useMovements,
  useWarehouses,
  useConfirmMovement,
  useCancelMovement,
  useDeleteMovement,
} from "../hooks";
import { useWarehouseNavigation } from "../hooks/useWarehouseNavigation";
import {
  MovementDto,
  MovementType,
  MovementStatus,
  movementTypeLabels,
  movementStatusLabels,
  getMovementTypeColor,
  getMovementStatusColor,
  formatDate,
} from "../types";

export default function MovementsPage() {
  const { t } = useTranslation();
  const [search, setSearch] = useState("");
  const [warehouseId, setWarehouseId] = useState<number | "">("");
  const [movementType, setMovementType] = useState<MovementType | "">("");
  const [status, setStatus] = useState<MovementStatus | "">("");
  const [dateFrom, setDateFrom] = useState<Dayjs | null>(null);
  const [dateTo, setDateTo] = useState<Dayjs | null>(null);
  const [menuAnchor, setMenuAnchor] = useState<null | HTMLElement>(null);
  const [menuMovement, setMenuMovement] = useState<MovementDto | null>(null);
  const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
  const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [speedDialOpen, setSpeedDialOpen] = useState(false);

  const nav = useWarehouseNavigation();

  const {
    data: movements,
    isLoading,
    error,
  } = useMovements({
    warehouseId: warehouseId || undefined,
    type: movementType !== "" ? movementType : undefined,
    status: status !== "" ? status : undefined,
    dateFrom: dateFrom?.format("YYYY-MM-DD"),
    dateTo: dateTo?.format("YYYY-MM-DD"),
  });

  const { data: warehouses } = useWarehouses();
  const confirmMutation = useConfirmMovement();
  const cancelMutation = useCancelMovement();
  const deleteMutation = useDeleteMovement();

  // Filter movements by search
  const filteredMovements = React.useMemo(() => {
    if (!movements) return [];
    if (!search) return movements;
    const lower = search.toLowerCase();
    return movements.filter(
      (m) =>
        m.documentNumber?.toLowerCase().includes(lower) ||
        m.externalReference?.toLowerCase().includes(lower) ||
        m.notes?.toLowerCase().includes(lower),
    );
  }, [movements, search]);

  const handleMenuOpen = (
    event: React.MouseEvent<HTMLElement>,
    movement: MovementDto,
  ) => {
    event.stopPropagation();
    setMenuAnchor(event.currentTarget);
    setMenuMovement(movement);
  };

  const handleMenuClose = () => {
    setMenuAnchor(null);
    setMenuMovement(null);
  };

  const handleView = () => {
    if (menuMovement) {
      nav.goToMovement(menuMovement.id);
    }
    handleMenuClose();
  };

  const handleConfirmClick = () => {
    setConfirmDialogOpen(true);
    setMenuAnchor(null);
  };

  const handleCancelClick = () => {
    setCancelDialogOpen(true);
    setMenuAnchor(null);
  };

  const handleDeleteClick = () => {
    setDeleteDialogOpen(true);
    setMenuAnchor(null);
  };

  const handleConfirmMovement = async () => {
    if (menuMovement) {
      await confirmMutation.mutateAsync(menuMovement.id);
      setConfirmDialogOpen(false);
      setMenuMovement(null);
    }
  };

  const handleCancelMovement = async () => {
    if (menuMovement) {
      await cancelMutation.mutateAsync(menuMovement.id);
      setCancelDialogOpen(false);
      setMenuMovement(null);
    }
  };

  const handleDeleteMovement = async () => {
    if (menuMovement) {
      await deleteMutation.mutateAsync(menuMovement.id);
      setDeleteDialogOpen(false);
      setMenuMovement(null);
    }
  };

  const clearFilters = () => {
    setSearch("");
    setWarehouseId("");
    setMovementType("");
    setStatus("");
    setDateFrom(null);
    setDateTo(null);
  };

  const columns: GridColDef<MovementDto>[] = [
    {
      field: "documentNumber",
      headerName: t("warehouse.movements.columns.document"),
      width: 140,
      renderCell: (params: GridRenderCellParams<MovementDto>) => (
        <Typography variant="body2" fontWeight="medium">
          {params.value || "-"}
        </Typography>
      ),
    },
    {
      field: "movementDate",
      headerName: t("warehouse.movements.columns.date"),
      width: 110,
      renderCell: (params: GridRenderCellParams<MovementDto>) =>
        formatDate(params.value),
    },
    {
      field: "type",
      headerName: t("warehouse.movements.columns.type"),
      width: 130,
      renderCell: (params: GridRenderCellParams<MovementDto>) => (
        <Chip
          label={t(`warehouse.movementType.${MovementType[params.value as MovementType]}`)}
          size="small"
          color={
            getMovementTypeColor(params.value as MovementType) as
            | "success"
            | "error"
            | "info"
            | "warning"
            | "default"
          }
        />
      ),
    },
    {
      field: "status",
      headerName: t("warehouse.movements.columns.status"),
      width: 120,
      renderCell: (params: GridRenderCellParams<MovementDto>) => (
        <Chip
          label={t(`warehouse.movementStatus.${MovementStatus[params.value as MovementStatus]}`)}
          size="small"
          color={
            getMovementStatusColor(params.value as MovementStatus) as
            | "success"
            | "error"
            | "warning"
            | "default"
          }
          variant={
            params.value === MovementStatus.Draft ? "outlined" : "filled"
          }
        />
      ),
    },
    {
      field: "sourceWarehouseName",
      headerName: t("warehouse.movements.columns.warehouse"),
      width: 150,
      renderCell: (params: GridRenderCellParams<MovementDto>) =>
        params.row.sourceWarehouseName ||
        params.row.destinationWarehouseName ||
        "-",
    },
    {
      field: "destinationWarehouseName",
      headerName: t("warehouse.movements.columns.destination"),
      width: 150,
      renderCell: (params: GridRenderCellParams<MovementDto>) => {
        // Show destination only for transfers
        if (params.row.type === MovementType.Transfer) {
          return params.row.destinationWarehouseName || "-";
        }
        return "-";
      },
    },
    {
      field: "reasonDescription",
      headerName: t("warehouse.movements.columns.reason"),
      width: 150,
      renderCell: (params: GridRenderCellParams<MovementDto>) =>
        params.value || "-",
    },
    {
      field: "lineCount",
      headerName: t("warehouse.movements.columns.lines"),
      width: 80,
      align: "center",
    },
    {
      field: "totalValue",
      headerName: t("warehouse.movements.columns.value"),
      width: 100,
      align: "right",
      renderCell: (params: GridRenderCellParams<MovementDto>) =>
        params.value != null
          ? new Intl.NumberFormat("it-IT", {
            style: "currency",
            currency: "EUR",
          }).format(params.value)
          : "-",
    },
    {
      field: "externalReference",
      headerName: t("warehouse.movements.columns.reference"),
      width: 140,
      renderCell: (params: GridRenderCellParams<MovementDto>) =>
        params.value || "-",
    },
    {
      field: "actions",
      headerName: "",
      width: 60,
      sortable: false,
      renderCell: (params: GridRenderCellParams<MovementDto>) => (
        <IconButton size="small" onClick={(e) => handleMenuOpen(e, params.row)}>
          <MoreVertIcon />
        </IconButton>
      ),
    },
  ];

  const speedDialActions = [
    { icon: <DownloadIcon />, name: t("warehouse.movements.actions.inbound"), action: nav.goToNewInbound },
    { icon: <UploadIcon />, name: t("warehouse.movements.actions.outbound"), action: nav.goToNewOutbound },
    {
      icon: <TransferIcon />,
      name: t("warehouse.movements.actions.transfer"),
      action: nav.goToNewTransfer,
    },
    {
      icon: <AdjustmentIcon />,
      name: t("warehouse.movements.actions.adjustment"),
      action: nav.goToNewAdjustment,
    },
  ];

  if (error) {
    return (
      <Box p={3}>
        <Alert severity="error">
          {t("warehouse.movements.loadingError", { error: (error as Error).message })}
        </Alert>
      </Box>
    );
  }

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="it">
      <Box>
        {/* Header */}
        <Box
          sx={{
            mb: 3,
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
          }}
        >
          <Typography variant="h5" fontWeight="bold">
            {t("warehouse.movements.title")}
          </Typography>
        </Box>

        {/* Filters */}
        <Paper sx={{ p: 2, mb: 3 }}>
          <Grid container spacing={2} alignItems="center">
            <Grid size={{ xs: 12, sm: 6, md: 3 }}>
              <TextField
                fullWidth
                size="small"
                placeholder={t("warehouse.movements.filters.searchPlaceholder")}
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                slotProps={{
                  input: {
                    startAdornment: (
                      <InputAdornment position="start">
                        <SearchIcon />
                      </InputAdornment>
                    ),
                    endAdornment: search && (
                      <InputAdornment position="end">
                        <IconButton size="small" onClick={() => setSearch("")}>
                          <ClearIcon />
                        </IconButton>
                      </InputAdornment>
                    ),
                  },
                }}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6, md: 2 }}>
              <FormControl fullWidth size="small">
                <InputLabel>{t("warehouse.movements.filters.warehouse")}</InputLabel>
                <Select
                  value={warehouseId}
                  label={t("warehouse.movements.filters.warehouse")}
                  onChange={(e) =>
                    setWarehouseId(e.target.value as number | "")
                  }
                >
                  <MenuItem value="">
                    <em>{t("warehouse.movements.filters.all")}</em>
                  </MenuItem>
                  {warehouses?.map((w) => (
                    <MenuItem key={w.id} value={w.id}>
                      {w.name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid size={{ xs: 6, sm: 4, md: 2 }}>
              <FormControl fullWidth size="small">
                <InputLabel>{t("warehouse.movements.filters.type")}</InputLabel>
                <Select
                  value={movementType}
                  label={t("warehouse.movements.filters.type")}
                  onChange={(e) =>
                    setMovementType(e.target.value as MovementType | "")
                  }
                >
                  <MenuItem value="">
                    <em>{t("warehouse.movements.filters.all")}</em>
                  </MenuItem>
                  {Object.entries(movementTypeLabels).map(([value]) => (
                    <MenuItem key={value} value={parseInt(value, 10)}>
                      {t(`warehouse.movementType.${MovementType[parseInt(value, 10)]}`)}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid size={{ xs: 6, sm: 4, md: 2 }}>
              <FormControl fullWidth size="small">
                <InputLabel>{t("warehouse.movements.filters.status")}</InputLabel>
                <Select
                  value={status}
                  label={t("warehouse.movements.filters.status")}
                  onChange={(e) =>
                    setStatus(e.target.value as MovementStatus | "")
                  }
                >
                  <MenuItem value="">
                    <em>{t("warehouse.movements.filters.all")}</em>
                  </MenuItem>
                  {Object.entries(movementStatusLabels).map(
                    ([value]) => (
                      <MenuItem key={value} value={parseInt(value, 10)}>
                        {t(`warehouse.movementStatus.${MovementStatus[parseInt(value, 10)]}`)}
                      </MenuItem>
                    ),
                  )}
                </Select>
              </FormControl>
            </Grid>
            <Grid size={{ xs: 6, sm: 4, md: 1.5 }}>
              <DatePicker
                label={t("warehouse.movements.filters.from")}
                value={dateFrom}
                onChange={setDateFrom}
                slotProps={{ textField: { size: "small", fullWidth: true } }}
              />
            </Grid>
            <Grid size={{ xs: 6, sm: 4, md: 1.5 }}>
              <DatePicker
                label={t("warehouse.movements.filters.to")}
                value={dateTo}
                onChange={setDateTo}
                slotProps={{ textField: { size: "small", fullWidth: true } }}
              />
            </Grid>
            {(search ||
              warehouseId ||
              movementType !== "" ||
              status !== "" ||
              dateFrom ||
              dateTo) && (
                <Grid size="auto">
                  <Button
                    size="small"
                    startIcon={<FilterIcon />}
                    onClick={clearFilters}
                  >
                    {t("warehouse.movements.filters.reset")}
                  </Button>
                </Grid>
              )}
          </Grid>
        </Paper>

        {/* Data Grid */}
        <Paper sx={{ height: 600 }}>
          <DataGrid
            rows={filteredMovements}
            columns={columns}
            loading={isLoading}
            pageSizeOptions={[25, 50, 100]}
            initialState={{
              pagination: { paginationModel: { pageSize: 25 } },
              sorting: { sortModel: [{ field: "movementDate", sort: "desc" }] },
            }}
            onRowDoubleClick={(params) => nav.goToMovement(params.row.id)}
            disableRowSelectionOnClick
            sx={{
              "& .MuiDataGrid-row:hover": {
                cursor: "pointer",
              },
            }}
          />
        </Paper>

        {/* Speed Dial for New Movements */}
        <SpeedDial
          ariaLabel={t("warehouse.movements.actions.newMovement")}
          sx={{ position: "fixed", bottom: 24, right: 24 }}
          icon={<SpeedDialIcon openIcon={<AddIcon />} />}
          open={speedDialOpen}
          onOpen={() => setSpeedDialOpen(true)}
          onClose={() => setSpeedDialOpen(false)}
        >
          {speedDialActions.map((action) => (
            <SpeedDialAction
              key={action.name}
              icon={action.icon}
              tooltipTitle={action.name}
              tooltipOpen
              onClick={() => {
                setSpeedDialOpen(false);
                action.action();
              }}
            />
          ))}
        </SpeedDial>

        {/* Context Menu */}
        <Menu
          anchorEl={menuAnchor}
          open={Boolean(menuAnchor)}
          onClose={handleMenuClose}
        >
          <MenuItem onClick={handleView}>
            <ListItemIcon>
              <ViewIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText>{t("warehouse.movements.actions.view")}</ListItemText>
          </MenuItem>
          {menuMovement?.status === MovementStatus.Draft && (
            <>
              <MenuItem onClick={handleConfirmClick}>
                <ListItemIcon>
                  <ConfirmIcon fontSize="small" color="success" />
                </ListItemIcon>
                <ListItemText>{t("warehouse.movements.actions.confirm")}</ListItemText>
              </MenuItem>
              <MenuItem onClick={handleCancelClick}>
                <ListItemIcon>
                  <CancelIcon fontSize="small" color="warning" />
                </ListItemIcon>
                <ListItemText>{t("warehouse.movements.actions.cancel")}</ListItemText>
              </MenuItem>
              <MenuItem
                onClick={handleDeleteClick}
                sx={{ color: "error.main" }}
              >
                <ListItemIcon>
                  <DeleteIcon fontSize="small" color="error" />
                </ListItemIcon>
                <ListItemText>{t("warehouse.movements.actions.delete")}</ListItemText>
              </MenuItem>
            </>
          )}
        </Menu>

        {/* Confirm Movement Dialog */}
        <Dialog
          open={confirmDialogOpen}
          onClose={() => setConfirmDialogOpen(false)}
        >
          <DialogTitle>{t("warehouse.movements.dialogs.confirm.title")}</DialogTitle>
          <DialogContent>
            <Typography>
              <Trans
                i18nKey="warehouse.movements.dialogs.confirm.content"
                values={{ doc: menuMovement?.documentNumber }}
                components={{ strong: <strong /> }}
              />
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
              {t("warehouse.movements.dialogs.confirm.warning")}
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setConfirmDialogOpen(false)}>{t("warehouse.movements.dialogs.confirm.cancel")}</Button>
            <Button
              onClick={handleConfirmMovement}
              color="success"
              variant="contained"
              disabled={confirmMutation.isPending}
            >
              {confirmMutation.isPending ? t("warehouse.movements.dialogs.confirm.confirming") : t("warehouse.movements.dialogs.confirm.confirm")}
            </Button>
          </DialogActions>
        </Dialog>

        {/* Cancel Movement Dialog */}
        <Dialog
          open={cancelDialogOpen}
          onClose={() => setCancelDialogOpen(false)}
        >
          <DialogTitle>{t("warehouse.movements.dialogs.cancel.title")}</DialogTitle>
          <DialogContent>
            <Typography>
              <Trans
                i18nKey="warehouse.movements.dialogs.cancel.content"
                values={{ doc: menuMovement?.documentNumber }}
                components={{ strong: <strong /> }}
              />
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
              {t("warehouse.movements.dialogs.cancel.warning")}
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setCancelDialogOpen(false)}>{t("warehouse.movements.dialogs.cancel.back")}</Button>
            <Button
              onClick={handleCancelMovement}
              color="warning"
              variant="contained"
              disabled={cancelMutation.isPending}
            >
              {cancelMutation.isPending
                ? t("warehouse.movements.dialogs.cancel.cancelling")
                : t("warehouse.movements.dialogs.cancel.cancelMovement")}
            </Button>
          </DialogActions>
        </Dialog>

        {/* Delete Movement Dialog */}
        <Dialog
          open={deleteDialogOpen}
          onClose={() => setDeleteDialogOpen(false)}
        >
          <DialogTitle>{t("warehouse.movements.dialogs.delete.title")}</DialogTitle>
          <DialogContent>
            <Typography>
              <Trans
                i18nKey="warehouse.movements.dialogs.delete.content"
                values={{ doc: menuMovement?.documentNumber }}
                components={{ strong: <strong /> }}
              />
            </Typography>
            <Typography variant="body2" color="error" sx={{ mt: 1 }}>
              {t("warehouse.movements.dialogs.delete.warning")}
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setDeleteDialogOpen(false)}>{t("warehouse.movements.dialogs.delete.cancel")}</Button>
            <Button
              onClick={handleDeleteMovement}
              color="error"
              variant="contained"
              disabled={deleteMutation.isPending}
            >
              {deleteMutation.isPending ? t("warehouse.movements.dialogs.delete.deleting") : t("warehouse.movements.dialogs.delete.delete")}
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
    </LocalizationProvider>
  );
}
