"use client";

import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults/SearchResults";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import { useRouter } from "next/navigation";
import { deleteDialog, successDialog } from "../Swal/CustomAlerts";
import { WarehouseResult } from "@/app/api/warehouse";
import { deleteWarehouse, editWarehouse } from "@/app/api/warehouse/actions";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import CardActions from "@mui/material/CardActions";
import Typography from "@mui/material/Typography";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import Box from "@mui/material/Box";
import RestartAlt from "@mui/icons-material/RestartAlt";
import Search from "@mui/icons-material/Search";
import InputAdornment from "@mui/material/InputAdornment";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import DialogActions from "@mui/material/DialogActions";

interface Props {
  warehouses: WarehouseResult[];
}

type SearchQuery = Partial<Omit<WarehouseResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const WarehouseHandle: React.FC<Props> = ({ warehouses }) => {
  const { t } = useTranslation(["warehouse", "common"]);
  const [filteredWarehouse, setFilteredWarehouse] = useState(warehouses);
  const [pagingController, setPagingController] = useState({
    pageNum: 1,
    pageSize: 10,
  });
  const router = useRouter();
  const [isSearching, setIsSearching] = useState(false);

  // State for editing order & stockTakeSection
  const [editingWarehouse, setEditingWarehouse] = useState<WarehouseResult | null>(null);
  const [editValues, setEditValues] = useState({
    order: "",
    stockTakeSection: "",
    stockTakeSectionDescription: "",
  });
  const [isSavingEdit, setIsSavingEdit] = useState(false);
  const [editError, setEditError] = useState("");

  const [searchInputs, setSearchInputs] = useState({
    store_id: "",
    warehouse: "",
    area: "",
    slot: "",
    stockTakeSection: "",
    stockTakeSectionDescription: "",
  });

  const onDeleteClick = useCallback((warehouse: WarehouseResult) => {
    deleteDialog(async () => {
      try {
        await deleteWarehouse(warehouse.id);
        setFilteredWarehouse(prev => prev.filter(w => w.id !== warehouse.id));
        router.refresh();
        successDialog(t("Delete Success"), t);
      } catch (error) {
        console.error("Failed to delete warehouse:", error);
      }
    }, t);
  }, [t, router]);

  const handleReset = useCallback(() => {
    setSearchInputs({
      store_id: "",
      warehouse: "",
      area: "",
      slot: "",
      stockTakeSection: "",
      stockTakeSectionDescription: "",
    });
    setFilteredWarehouse(warehouses);
    setPagingController({ pageNum: 1, pageSize: pagingController.pageSize });
  }, [warehouses, pagingController.pageSize]);

  const onEditClick = useCallback((warehouse: WarehouseResult) => {
    setEditingWarehouse(warehouse);
    setEditValues({
      order: warehouse.order ?? "",
      stockTakeSection: warehouse.stockTakeSection ?? "",
      stockTakeSectionDescription: warehouse.stockTakeSectionDescription ?? "",
    });
    setEditError("");
  }, []);

  const handleEditClose = useCallback(() => {
    if (isSavingEdit) return;
    setEditingWarehouse(null);
    setEditError("");
  }, [isSavingEdit]);

  const handleEditSave = useCallback(async () => {
    if (!editingWarehouse) return;

    const trimmedOrder = editValues.order.trim();
    const trimmedStockTakeSection = editValues.stockTakeSection.trim();
    const trimmedStockTakeSectionDescription = editValues.stockTakeSectionDescription.trim();
    const orderPattern = /^[A-Za-z0-9]{2}-[A-Za-z0-9]{3}$/;
    const sectionPattern = /^[A-Za-z0-9]{2}-[A-Za-z0-9]{3}$/;

    if (trimmedOrder && !orderPattern.test(trimmedOrder)) {
      setEditError(`${t("order")} 格式必須為 XF-YYY`);
      return;
    }

    if (trimmedStockTakeSection && !sectionPattern.test(trimmedStockTakeSection)) {
      setEditError(`${t("stockTakeSection")} 格式必須為 ST-YYY`);
      return;
    }

    try {
      setIsSavingEdit(true);
      setEditError("");

      await editWarehouse(editingWarehouse.id, {
        order: trimmedOrder || undefined,
        stockTakeSection: trimmedStockTakeSection || undefined,
        stockTakeSectionDescription: trimmedStockTakeSectionDescription || undefined,
      });

      setFilteredWarehouse((prev) =>
        prev.map((w) =>
          w.id === editingWarehouse.id
            ? {
                ...w,
                order: trimmedOrder || undefined,
                stockTakeSection: trimmedStockTakeSection || undefined,
                stockTakeSectionDescription: trimmedStockTakeSectionDescription || undefined,
              }
            : w,
        ),
      );

      router.refresh();
      setEditingWarehouse(null);
    } catch (error: unknown) {
      console.error("Failed to edit warehouse:", error);
      const message = error instanceof Error ? error.message : t("An error has occurred. Please try again later.");
      setEditError(message);
    } finally {
      setIsSavingEdit(false);
    }
  }, [editValues, editingWarehouse, router, t, setFilteredWarehouse]);

  const handleSearch = useCallback(() => {
    setIsSearching(true);
    try {
      let results: WarehouseResult[] = warehouses;

      const storeId = searchInputs.store_id?.trim() || "";
      const warehouse = searchInputs.warehouse?.trim() || "";
      const area = searchInputs.area?.trim() || "";
      const slot = searchInputs.slot?.trim() || "";
      const stockTakeSection = searchInputs.stockTakeSection?.trim() || "";
      const stockTakeSectionDescription = searchInputs.stockTakeSectionDescription?.trim() || "";
      if (storeId || warehouse || area || slot || stockTakeSection || stockTakeSectionDescription) {
        results = warehouses.filter((warehouseItem) => {
          if (stockTakeSection) {
            const itemStockTakeSection = String(warehouseItem.stockTakeSection || "").toLowerCase();
            if (!itemStockTakeSection.includes(stockTakeSection.toLowerCase())) {
              return false;
            }
          }
          if (stockTakeSectionDescription) {
            const itemStockTakeSectionDescription = String(warehouseItem.stockTakeSectionDescription || "").toLowerCase();
            if (!itemStockTakeSectionDescription.includes(stockTakeSectionDescription.toLowerCase())) {
              return false;
            }
          }
          if (storeId || warehouse || area || slot) {
            if (!warehouseItem.code) {
              return false;
            }
            
            const codeValue = String(warehouseItem.code).toLowerCase();
            
            const codeParts = codeValue.split("-");
            
            if (codeParts.length >= 4) {
              const codeStoreId = codeParts[0] || "";
              const codeWarehouse = codeParts[1] || "";
              const codeArea = codeParts[2] || "";
              const codeSlot = codeParts[3] || "";
              
              const storeIdMatch = !storeId || codeStoreId.includes(storeId.toLowerCase());
              const warehouseMatch = !warehouse || codeWarehouse.includes(warehouse.toLowerCase());
              const areaMatch = !area || codeArea.includes(area.toLowerCase());
              const slotMatch = !slot || codeSlot.includes(slot.toLowerCase());
              
              return storeIdMatch && warehouseMatch && areaMatch && slotMatch;
            }
            
            const storeIdMatch = !storeId || codeValue.includes(storeId.toLowerCase());
            const warehouseMatch = !warehouse || codeValue.includes(warehouse.toLowerCase());
            const areaMatch = !area || codeValue.includes(area.toLowerCase());
            const slotMatch = !slot || codeValue.includes(slot.toLowerCase());
            
            return storeIdMatch && warehouseMatch && areaMatch && slotMatch;
          }
          
          return true;
        });
      } else {
        results = warehouses;
      }

      setFilteredWarehouse(results);
      setPagingController({ pageNum: 1, pageSize: pagingController.pageSize });
    } catch (error) {
      console.error("Error searching warehouses:", error);
      const storeId = searchInputs.store_id?.trim().toLowerCase() || "";
      const warehouse = searchInputs.warehouse?.trim().toLowerCase() || "";
      const area = searchInputs.area?.trim().toLowerCase() || "";
      const slot = searchInputs.slot?.trim().toLowerCase() || "";
      const stockTakeSection = searchInputs.stockTakeSection?.trim().toLowerCase() || "";
      const stockTakeSectionDescription = searchInputs.stockTakeSectionDescription?.trim().toLowerCase() || "";
      setFilteredWarehouse(
        warehouses.filter((warehouseItem) => {
          if (stockTakeSection) {
            const itemStockTakeSection = String(warehouseItem.stockTakeSection || "").toLowerCase();
            if (!itemStockTakeSection.includes(stockTakeSection)) {
              return false;
            }
          }
          if (stockTakeSectionDescription) {
            const itemStockTakeSectionDescription = String(warehouseItem.stockTakeSectionDescription || "").toLowerCase();
            if (!itemStockTakeSectionDescription.includes(stockTakeSectionDescription)) {
              return false;
            }
          }
          if (storeId || warehouse || area || slot) {
            if (!warehouseItem.code) {
              return false;
            }
            
            const codeValue = String(warehouseItem.code).toLowerCase();
            const codeParts = codeValue.split("-");
            
            if (codeParts.length >= 4) {
              const storeIdMatch = !storeId || codeParts[0].includes(storeId);
              const warehouseMatch = !warehouse || codeParts[1].includes(warehouse);
              const areaMatch = !area || codeParts[2].includes(area);
              const slotMatch = !slot || codeParts[3].includes(slot);
              return storeIdMatch && warehouseMatch && areaMatch && slotMatch;
            }
            
            return (!storeId || codeValue.includes(storeId)) &&
                   (!warehouse || codeValue.includes(warehouse)) &&
                   (!area || codeValue.includes(area)) &&
                   (!slot || codeValue.includes(slot));
          }
          
          return true;
        })
      );
    } finally {
      setIsSearching(false);
    }
  }, [searchInputs, warehouses, pagingController.pageSize]);

  const columns = useMemo<Column<WarehouseResult>[]>(
    () => [
      {
        name: "action",
        label: t("Edit"),
        onClick: onEditClick,
        buttonIcon: <EditIcon />,
        color: "primary",
        sx: { width: "10%", minWidth: "80px" },
      },
      { 
        name: "code", 
        label: t("code"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: "120px" },
      },
      { 
        name: "store_id", 
        label: t("store_id"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: "120px" },
      },
      { 
        name: "warehouse", 
        label: t("warehouse"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: "120px" },
      },
      { 
        name: "area", 
        label: t("area"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: "120px" },
      },
      { 
        name: "slot", 
        label: t("slot"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: "120px" },
      },
      { 
        name: "order", 
        label: t("order"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: "120px" },
      },
      { 
        name: "stockTakeSection", 
        label: t("stockTakeSection"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: "120px" },
      },
      { 
        name: "stockTakeSectionDescription", 
        label: t("stockTakeSectionDescription"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: "120px" },
      },
      {
        name: "action",
        label: t("Delete"),
        onClick: onDeleteClick,
        buttonIcon: <DeleteIcon />,
        color: "error",
        sx: { width: "10%", minWidth: "80px" },
      },
    ],
    [t, onDeleteClick],
  );

  return (
    <>
      <Card>
        <CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
          <Typography variant="overline">{t("Search Criteria")}</Typography>
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              gap: 1,
              flexWrap: "nowrap",
              justifyContent: "flex-start",
            }}
          >
            <TextField
              label={t("store_id")}
              value={searchInputs.store_id}
              onChange={(e) =>
                setSearchInputs((prev) => ({ ...prev, store_id: e.target.value }))
              }
              size="small"
              sx={{ width: "150px", minWidth: "120px" }}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">F</InputAdornment>
                ),
              }}
            />
            <Typography variant="body1" sx={{ mx: 0.5 }}>
              -
            </Typography>
            <TextField
              label={t("warehouse")}
              value={searchInputs.warehouse}
              onChange={(e) =>
                setSearchInputs((prev) => ({ ...prev, warehouse: e.target.value }))
              }
              size="small"
              sx={{ width: "150px", minWidth: "120px" }}
            />
            <Typography variant="body1" sx={{ mx: 0.5 }}>
              -
            </Typography>
            <TextField
              label={t("area")}
              value={searchInputs.area}
              onChange={(e) =>
                setSearchInputs((prev) => ({ ...prev, area: e.target.value }))
              }
              size="small"
              sx={{ width: "150px", minWidth: "120px" }}
            />
            <Typography variant="body1" sx={{ mx: 0.5 }}>
              -
            </Typography>
            <TextField
              label={t("slot")}
              value={searchInputs.slot}
              onChange={(e) =>
                setSearchInputs((prev) => ({ ...prev, slot: e.target.value }))
              }
              size="small"
              sx={{ width: "150px", minWidth: "120px" }}
            />
            <Box sx={{ flex: 1, minWidth: "150px", ml: 2 }}>
              <TextField
                label={t("stockTakeSection")}
                value={searchInputs.stockTakeSection}
                onChange={(e) =>
                  setSearchInputs((prev) => ({ ...prev, stockTakeSection: e.target.value }))
                }
                size="small"
                fullWidth
              />
            </Box>
            <Box sx={{ flex: 1, minWidth: "150px", ml: 2 }}>
              <TextField
                label={t("stockTakeSectionDescription")}
                value={searchInputs.stockTakeSectionDescription}
                onChange={(e) =>
                  setSearchInputs((prev) => ({ ...prev, stockTakeSectionDescription: e.target.value }))
                }
                size="small"
                fullWidth
              />
            </Box>
          </Box>
          <CardActions sx={{ justifyContent: "flex-start", px: 0, pt: 1 }}>
            <Button
              variant="text"
              startIcon={<RestartAlt />}
              onClick={handleReset}
            >
              {t("Reset")}
            </Button>
            <Button
              variant="outlined"
              startIcon={<Search />}
              onClick={handleSearch}
            >
              {t("Search")}
            </Button>
          </CardActions>
        </CardContent>
      </Card>
      <SearchResults<WarehouseResult>
        items={filteredWarehouse}
        columns={columns}
        pagingController={pagingController}
        setPagingController={setPagingController}
      />
      <Dialog
        open={Boolean(editingWarehouse)}
        onClose={handleEditClose}
        fullWidth
        maxWidth="sm"
      >
        <DialogTitle>{t("Edit")}</DialogTitle>
        <DialogContent sx={{ pt: 2, display: "flex", flexDirection: "column", gap: 2 }}>
          {editError && (
            <Typography variant="body2" color="error">
              {editError}
            </Typography>
          )}
          <TextField
            label={t("order")}
            value={editValues.order}
            onChange={(e) =>
              setEditValues((prev) => ({ ...prev, order: e.target.value }))
            }
            size="small"
            fullWidth
          />
          <TextField
            label={t("stockTakeSection")}
            value={editValues.stockTakeSection}
            onChange={(e) =>
              setEditValues((prev) => ({ ...prev, stockTakeSection: e.target.value }))
            }
            size="small"
            fullWidth
          />
          <TextField
            label={t("stockTakeSectionDescription")}
            value={editValues.stockTakeSectionDescription}
            onChange={(e) =>
              setEditValues((prev) => ({ ...prev, stockTakeSectionDescription: e.target.value }))
            }
            size="small"
            fullWidth
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleEditClose} disabled={isSavingEdit}>
            {t("Cancel")}
          </Button>
          <Button
            onClick={handleEditSave}
            disabled={isSavingEdit}
            variant="contained"
          >
            {t("Save", { ns: "common" })}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};
export default WarehouseHandle;
