"use client";

import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  CircularProgress,
  Alert,
  Grid,
  Stack,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Snackbar,
  TextField,
  Autocomplete,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import SaveIcon from "@mui/icons-material/Save";
import CancelIcon from "@mui/icons-material/Cancel";
import AddIcon from "@mui/icons-material/Add";
import CheckIcon from "@mui/icons-material/Check";
import CloseIcon from "@mui/icons-material/Close";
import { useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslation } from "react-i18next";
import {
  findAllUniqueTruckLaneCombinationsClient,
  findAllShopsByTruckLanceCodeClient,
  deleteTruckLaneClient,
  updateTruckShopDetailsClient,
  fetchAllShopsClient,
  findAllUniqueShopNamesAndCodesFromTrucksClient,
  findAllUniqueRemarksFromTrucksClient,
  findAllUniqueShopCodesFromTrucksClient,
  findAllUniqueShopNamesFromTrucksClient,
  createTruckClient,
  findAllByTruckLanceCodeAndDeletedFalseClient,
  updateTruckLaneClient,
} from "@/app/api/shop/client";
import type { Truck, ShopAndTruck, Shop } from "@/app/api/shop/actions";
import { formatDepartureTime, normalizeStoreId } from "@/app/utils/formatUtil";

const parseDepartureTimeForBackend = (time: string): string => {
  if (!time) return "";
  const timeStr = String(time).trim();
  if (/^\d{1,2}:\d{2}$/.test(timeStr)) {
    return timeStr;
  }
  return formatDepartureTime(timeStr);
};

/** HH:mm for HTML time input from API truck departureTime. */
const truckDepartureTimeToInputValue = (timeValue: Truck["departureTime"]): string => {
  const formatted = formatDepartureTime(
    Array.isArray(timeValue) ? timeValue : timeValue ? String(timeValue) : null
  );
  return formatted !== "-" ? formatted : "";
};

const TruckLaneDetail: React.FC = () => {
  const { t } = useTranslation("shop");
  const router = useRouter();
  const searchParams = useSearchParams();
  const truckLanceCodeParam = searchParams.get("truckLanceCode");
  // Decode the truckLanceCode to handle special characters properly
  const truckLanceCode = truckLanceCodeParam ? decodeURIComponent(truckLanceCodeParam) : null;
  
  const [truckData, setTruckData] = useState<Truck | null>(null);
  const [shopsData, setShopsData] = useState<ShopAndTruck[]>([]);
  const [editedShopsData, setEditedShopsData] = useState<ShopAndTruck[]>([]);
  const [editingRowIndex, setEditingRowIndex] = useState<number | null>(null);
  const [massEditing, setMassEditing] = useState<boolean>(false);
  const [confirmingDeleteIndex, setConfirmingDeleteIndex] = useState<number | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [shopsLoading, setShopsLoading] = useState<boolean>(false);
  const [saving, setSaving] = useState<boolean>(false);
  const [savingDepartureTime, setSavingDepartureTime] = useState<boolean>(false);
  const [editingDepartureTime, setEditingDepartureTime] = useState<boolean>(false);
  const [departureTimeEdit, setDepartureTimeEdit] = useState<string>("");
  const [error, setError] = useState<string | null>(null);
  const [allShops, setAllShops] = useState<Shop[]>([]);
  const [shopTableList, setShopTableList] = useState<ShopAndTruck[]>([]);
  const [uniqueRemarks, setUniqueRemarks] = useState<string[]>([]);
  const [shopNameByCodeMap, setShopNameByCodeMap] = useState<Map<string, string>>(new Map());
  const [addShopDialogOpen, setAddShopDialogOpen] = useState<boolean>(false);
  const [newShop, setNewShop] = useState({
    shopName: "",
    shopCode: "",
    shopBranch: "",
    loadingSequence: 0,
    remark: "",
  });
  const [snackbar, setSnackbar] = useState<{ open: boolean; message: string; severity: "success" | "error" }>({
    open: false,
    message: "",
    severity: "success",
  });

  // Fetch autocomplete data on mount
  useEffect(() => {
    const fetchAutocompleteData = async () => {
      try {
        const [shopData, remarks, , , allShopsFromShopTable] = await Promise.all([
          findAllUniqueShopNamesAndCodesFromTrucksClient() as Promise<Array<{ name: string; code: string }>>,
          findAllUniqueRemarksFromTrucksClient() as Promise<string[]>,
          findAllUniqueShopCodesFromTrucksClient() as Promise<string[]>,
          findAllUniqueShopNamesFromTrucksClient() as Promise<string[]>,
          fetchAllShopsClient() as Promise<ShopAndTruck[]>,
        ]);

        // Convert to Shop format (id will be 0 since we don't have shop IDs from truck table)
        const shopList: Shop[] = shopData.map((shop) => ({
          id: 0,
          name: shop.name || "",
          code: shop.code || "",
          addr3: "",
        }));
        
        setAllShops(shopList);
        setUniqueRemarks(remarks || []);

        // Create lookup map: shopCode -> shopName from shop table
        const shopNameMap = new Map<string, string>();
        (allShopsFromShopTable || []).forEach((shop) => {
          if (shop.code) {
            shopNameMap.set(String(shop.code).trim().toLowerCase(), String(shop.name || "").trim());
          }
        });
        setShopNameByCodeMap(shopNameMap);

        // Deduplicate shop table entries by code
        const seen = new Set<string>();
        const uniqueShops = (allShopsFromShopTable || []).filter((shop) => {
          const code = String(shop.code || "").trim().toLowerCase();
          if (!code || seen.has(code)) return false;
          seen.add(code);
          return true;
        });
        setShopTableList(uniqueShops);
      } catch (err) {
        console.error("Failed to load autocomplete data:", err);
      }
    };

    fetchAutocompleteData();
  }, []);

  useEffect(() => {
    if (!truckData) {
      setDepartureTimeEdit("");
      return;
    }
    if (!editingDepartureTime) {
      setDepartureTimeEdit(truckDepartureTimeToInputValue(truckData.departureTime));
    }
  }, [truckData, editingDepartureTime]);

  useEffect(() => {
    // Wait a bit to ensure searchParams are fully available
    if (!truckLanceCodeParam) {
      setError(t("TruckLance Code is required"));
      setLoading(false);
      return;
    }

    const fetchTruckLaneDetail = async () => {
      if (!truckLanceCode) {
        setError(t("TruckLance Code is required"));
        setLoading(false);
        return;
      }

      setLoading(true);
      setError(null);
      try {
        const data = await findAllUniqueTruckLaneCombinationsClient() as Truck[];
        const truck = data.find((t) => String(t.truckLanceCode || "").trim() === truckLanceCode.trim());
        
        if (truck) {
          setTruckData(truck);
          // Fetch shops using this truck lane code only
          await fetchShopsByTruckLane(truckLanceCode);
        } else {
          setError(t("Truck lane not found"));
        }
      } catch (err: any) {
        console.error("Failed to load truck lane detail:", err);
        // Don't show error if it's a 401 - that will be handled by the auth system
        if (err?.message?.includes("401") || err?.status === 401) {
          // Let the auth system handle the redirect
          return;
        }
        setError(err?.message ?? String(err) ?? t("Failed to load truck lane detail"));
      } finally {
        setLoading(false);
      }
    };

    fetchTruckLaneDetail();
  }, [truckLanceCode, truckLanceCodeParam, t]);

  const fetchShopsByTruckLane = async (truckLanceCode: string) => {
    setShopsLoading(true);
    try {
      // Fetch shops by truckLanceCode only
      const shops = await findAllShopsByTruckLanceCodeClient(truckLanceCode);
      // Sort by remarks, then loadingSequence, then code
      const sortedShops = (shops || []).sort((a, b) => {
        const remarkA = String(a.remark || "").trim();
        const remarkB = String(b.remark || "").trim();
        if (remarkA !== remarkB) {
          return remarkA.localeCompare(remarkB);
        }
        const seqA = (a as any).LoadingSequence ?? (a as any).loadingSequence ?? 0;
        const seqB = (b as any).LoadingSequence ?? (b as any).loadingSequence ?? 0;
        if (Number(seqA) !== Number(seqB)) {
          return Number(seqA) - Number(seqB);
        }
        const codeA = String(a.code || "").trim();
        const codeB = String(b.code || "").trim();
        return codeA.localeCompare(codeB);
      });
      setShopsData(sortedShops);
      setEditedShopsData(sortedShops);
    } catch (err: any) {
      console.error("Failed to load shops:", err);
      setSnackbar({
        open: true,
        message: err?.message ?? String(err) ?? t("Failed to load shops"),
        severity: "error",
      });
    } finally {
      setShopsLoading(false);
    }
  };

  const handleSaveDepartureTimeForAllShops = async () => {
    if (!truckLanceCode || !truckData) {
      setSnackbar({
        open: true,
        message: t("Truck lane information is required"),
        severity: "error",
      });
      return;
    }

    let departureTimeStr = String(departureTimeEdit || "").trim();
    if (!departureTimeStr) {
      setSnackbar({
        open: true,
        message: `${t("Please fill in the following required fields:")} ${t("Departure Time")}`,
        severity: "error",
      });
      return;
    }
    departureTimeStr = parseDepartureTimeForBackend(departureTimeStr);
    if (!departureTimeStr) {
      setSnackbar({
        open: true,
        message: t("Invalid departure time"),
        severity: "error",
      });
      return;
    }

    setSavingDepartureTime(true);
    try {
      const rows = (await findAllByTruckLanceCodeAndDeletedFalseClient(truckLanceCode)) as Truck[];
      const withIds = (rows || []).filter((r) => r.id != null);
      if (withIds.length === 0) {
        setSnackbar({
          open: true,
          message: t("No trucks found for this truck lane"),
          severity: "error",
        });
        return;
      }

      await Promise.all(
        withIds.map((row) => {
          const storeIdStr = normalizeStoreId(row.storeId) || "2F";
          let remarkValue: string | null = null;
          if (storeIdStr === "4F" && row.remark != null && String(row.remark).trim() !== "") {
            remarkValue = String(row.remark).trim();
          }
          return updateTruckLaneClient({
            id: row.id!,
            truckLanceCode: String(row.truckLanceCode || ""),
            departureTime: departureTimeStr,
            loadingSequence: Number(row.loadingSequence) || 0,
            districtReference:
              row.districtReference != null && String(row.districtReference).trim() !== ""
                ? String(row.districtReference)
                : null,
            storeId: storeIdStr,
            remark: remarkValue,
          });
        })
      );

      setSnackbar({
        open: true,
        message: t("Departure time updated for all shops on this truck lane"),
        severity: "success",
      });

      const data = (await findAllUniqueTruckLaneCombinationsClient()) as Truck[];
      const truck = data.find((t) => String(t.truckLanceCode || "").trim() === truckLanceCode.trim());
      if (truck) {
        setTruckData(truck);
      }
      await fetchShopsByTruckLane(truckLanceCode);
      setEditingDepartureTime(false);
    } catch (err: any) {
      console.error("Failed to update departure time for truck lane:", err);
      setSnackbar({
        open: true,
        message: err?.message ?? String(err) ?? t("Failed to save truck data"),
        severity: "error",
      });
    } finally {
      setSavingDepartureTime(false);
    }
  };

  const handleCancelDepartureTimeEdit = () => {
    if (truckData) {
      setDepartureTimeEdit(truckDepartureTimeToInputValue(truckData.departureTime));
    }
    setEditingDepartureTime(false);
  };

  const handleEdit = (index: number) => {
    setEditingRowIndex(index);
    const updated = [...shopsData];
    updated[index] = { ...updated[index] };
    setEditedShopsData(updated);
  };

  const handleCancel = (index: number) => {
    setEditingRowIndex(null);
    setEditedShopsData([...shopsData]);
  };

  const handleSave = async (index: number) => {
    const shop = editedShopsData[index];
    const original = shopsData[index];
    if (!shop || !shop.truckId) {
      setSnackbar({ open: true, message: t("Invalid shop data"), severity: "error" });
      return;
    }

    setSaving(true);
    setError(null);
    try {
      const loadingSeq = (shop as any)?.LoadingSequence ?? (shop as any)?.loadingSequence;
      const loadingSequenceValue = (loadingSeq !== null && loadingSeq !== undefined) ? Number(loadingSeq) : 0;
      const remarkValue = shop.remark ? String(shop.remark).trim() : null;

      await updateTruckShopDetailsClient({
        id: shop.truckId,
        shopId: original.id && original.id > 0 ? original.id : null,
        shopName: original.name ? String(original.name).trim() : null,
        shopCode: original.code ? String(original.code).trim() : null,
        loadingSequence: loadingSequenceValue,
        remark: remarkValue,
      });

      setSnackbar({ open: true, message: t("Truck shop details updated successfully"), severity: "success" });

      if (truckLanceCode) {
        await fetchShopsByTruckLane(truckLanceCode);
      }
      setEditingRowIndex(null);
    } catch (err: any) {
      console.error("Failed to save truck shop details:", err);
      setSnackbar({
        open: true,
        message: err?.message ?? String(err) ?? t("Failed to save truck shop details"),
        severity: "error",
      });
    } finally {
      setSaving(false);
    }
  };

  const handleStartMassEdit = () => {
    setEditedShopsData([...shopsData].map((s) => ({ ...s })));
    setMassEditing(true);
    setEditingRowIndex(null);
  };

  const handleCancelMassEdit = () => {
    setMassEditing(false);
    setEditedShopsData([...shopsData]);
  };

  const handleSaveMassEdit = async () => {
    const rowsToSave = editedShopsData.filter((s) => s.truckId != null);
    if (rowsToSave.length === 0) return;

    setSaving(true);
    setError(null);
    try {
      await Promise.all(
        rowsToSave.map((shop, idx) => {
          const original = shopsData[idx];
          const loadingSeq = (shop as any)?.LoadingSequence ?? (shop as any)?.loadingSequence;
          const loadingSequenceValue = (loadingSeq !== null && loadingSeq !== undefined) ? Number(loadingSeq) : 0;
          const remarkValue = shop.remark ? String(shop.remark).trim() : null;

          return updateTruckShopDetailsClient({
            id: shop.truckId!,
            shopId: original.id && original.id > 0 ? original.id : null,
            shopName: original.name ? String(original.name).trim() : null,
            shopCode: original.code ? String(original.code).trim() : null,
            loadingSequence: loadingSequenceValue,
            remark: remarkValue,
          });
        })
      );

      setSnackbar({ open: true, message: t("All shops updated successfully"), severity: "success" });
      setMassEditing(false);
      if (truckLanceCode) {
        await fetchShopsByTruckLane(truckLanceCode);
      }
    } catch (err: any) {
      console.error("Failed to mass save:", err);
      setSnackbar({
        open: true,
        message: err?.message ?? String(err) ?? t("Failed to save truck shop details"),
        severity: "error",
      });
    } finally {
      setSaving(false);
    }
  };

  const handleLoadingSequenceChange = (index: number, value: string) => {
    const updated = [...editedShopsData];
    const numValue = parseInt(value, 10);
    updated[index] = {
      ...updated[index],
      LoadingSequence: isNaN(numValue) ? 0 : numValue,
    };
    setEditedShopsData(updated);
  };

  const handleRemarkChange = (index: number, value: string) => {
    const updated = [...editedShopsData];
    updated[index] = {
      ...updated[index],
      remark: value,
    };
    setEditedShopsData(updated);
  };

  const handleDelete = async (truckIdToDelete: number) => {
    try {
      await deleteTruckLaneClient({ id: truckIdToDelete });
      setSnackbar({
        open: true,
        message: t("Truck lane deleted successfully"),
        severity: "success",
      });
      setConfirmingDeleteIndex(null);

      if (truckLanceCode) {
        await fetchShopsByTruckLane(truckLanceCode);
      }
    } catch (err: any) {
      console.error("Failed to delete truck lane:", err);
      setSnackbar({
        open: true,
        message: err?.message ?? String(err) ?? t("Failed to delete truck lane"),
        severity: "error",
      });
    }
  };

  const handleBack = () => {
    router.push("/settings/shop/board");
  };

  const handleOpenAddShopDialog = () => {
    setNewShop({
      shopName: "",
      shopCode: "",
      shopBranch: "",
      loadingSequence: 0,
      remark: "",
    });
    setAddShopDialogOpen(true);
    setError(null);
  };

  const handleCloseAddShopDialog = () => {
    setAddShopDialogOpen(false);
    setNewShop({
      shopName: "",
      shopCode: "",
      shopBranch: "",
      loadingSequence: 0,
      remark: "",
    });
  };

  const handleNewShopNameChange = (selectedShop: ShopAndTruck | null) => {
    if (selectedShop) {
      const shopCode = String(selectedShop.code || "").trim();
      const shopTableName = String(selectedShop.name || "").trim();

      // Auto-fill branch: use the first existing branch name from the
      // truck table for this shopCode, falling back to the shop table name.
      const existingBranch = allShops.find(
        (s) =>
          String(s.code).trim().toLowerCase() === shopCode.toLowerCase() &&
          String(s.name || "").trim() !== "" &&
          String(s.name || "").trim().toLowerCase() !== "unassign"
      );

      setNewShop({
        ...newShop,
        shopName: shopTableName,
        shopCode: shopCode,
        shopBranch: existingBranch ? String(existingBranch.name).trim() : shopTableName,
      });
    } else {
      setNewShop({
        ...newShop,
        shopName: "",
        shopCode: "",
        shopBranch: "",
      });
    }
  };

  const handleCreateShop = async () => {
    const missingFields: string[] = [];

    if (!newShop.shopName.trim()) {
      missingFields.push(t("Shop Name"));
    }

    if (missingFields.length > 0) {
      setSnackbar({
        open: true,
        message: `${t("Please fill in the following required fields:")} ${missingFields.join(", ")}`,
        severity: "error",
      });
      return;
    }

    if (!truckData || !truckLanceCode) {
      setSnackbar({
        open: true,
        message: t("Truck lane information is required"),
        severity: "error",
      });
      return;
    }

    setSaving(true);
    setError(null);
    try {
      const storeIdValue = truckData.storeId ? (typeof truckData.storeId === 'string' || truckData.storeId instanceof String 
        ? String(truckData.storeId) 
        : String(truckData.storeId)) : "2F";
      const displayStoreId = normalizeStoreId(storeIdValue) || "2F";

      let departureTimeStr = "";
      if (truckData.departureTime) {
        if (Array.isArray(truckData.departureTime)) {
          const [hours, minutes] = truckData.departureTime;
          departureTimeStr = `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}`;
        } else {
          departureTimeStr = String(truckData.departureTime);
        }
      }

      const foundShop = shopTableList.find(
        (s) => String(s.code).trim() === newShop.shopCode.trim()
      );
      const shopIdValue = foundShop ? foundShop.id : null;

      // Get remark - only if storeId is "4F"
      const remarkValue = displayStoreId === "4F" ? (newShop.remark?.trim() || null) : null;

      // Check if there's an "Unassign" row for this truck lane that should be replaced
      let unassignTruck: Truck | null = null;
      try {
        const allTrucks = await findAllByTruckLanceCodeAndDeletedFalseClient(String(truckData.truckLanceCode || "")) as Truck[];
        unassignTruck = allTrucks.find(t => 
          String(t.shopName || "").trim() === "Unassign" && 
          String(t.shopCode || "").trim() === "Unassign"
        ) || null;
      } catch (err) {
        console.error("Failed to check for Unassign truck:", err);
      }

      if (unassignTruck && unassignTruck.id) {
        // Update the existing "Unassign" row instead of creating a new one
        await updateTruckShopDetailsClient({
          id: unassignTruck.id,
          shopId: shopIdValue || null,
          shopName: newShop.shopBranch.trim(),
          shopCode: newShop.shopCode.trim(),
          loadingSequence: newShop.loadingSequence,
          remark: remarkValue,
        });

        setSnackbar({
          open: true,
          message: t("Shop added to truck lane successfully"),
          severity: "success",
        });
      } else {
        // No "Unassign" row found, create a new one
        await createTruckClient({
          store_id: displayStoreId,
          truckLanceCode: String(truckData.truckLanceCode || ""),
          departureTime: departureTimeStr,
          shopId: shopIdValue || 0,
          shopName: newShop.shopBranch.trim(),
          shopCode: newShop.shopCode.trim(),
          loadingSequence: newShop.loadingSequence,
          remark: remarkValue,
          districtReference: null,
        });

        setSnackbar({
          open: true,
          message: t("Shop added to truck lane successfully"),
          severity: "success",
        });
      }

      // Refresh the shops list
      if (truckLanceCode) {
        await fetchShopsByTruckLane(truckLanceCode);
      }
      
      handleCloseAddShopDialog();
    } catch (err: any) {
      console.error("Failed to create shop in truck lane:", err);
      setSnackbar({
        open: true,
        message: err?.message ?? String(err) ?? t("Failed to create shop in truck lane"),
        severity: "error",
      });
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <Box sx={{ display: "flex", justifyContent: "center", p: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Box>
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
        <Button variant="contained" onClick={handleBack}>
          {t("Back to Truck Lane List")}
        </Button>
      </Box>
    );
  }

  if (!truckData) {
    return (
      <Box>
        <Alert severity="warning" sx={{ mb: 2 }}>
          {t("No truck lane data available")}
        </Alert>
        <Button variant="contained" onClick={handleBack}>
          {t("Back to Truck Lane List")}
        </Button>
      </Box>
    );
  }

  const displayStoreId = normalizeStoreId(
    truckData.storeId ? (typeof truckData.storeId === 'string' || truckData.storeId instanceof String 
      ? String(truckData.storeId) 
      : String(truckData.storeId)) : null
  );

  return (
    <Box>
      <Card sx={{ mb: 2 }}>
        <CardContent>
          <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", mb: 2 }}>
            <Typography variant="h5">{t("Truck Lane Detail")}</Typography>
            <Button variant="outlined" onClick={handleBack}>
              {t("Back to Truck Lane List")}
            </Button>
          </Box>
        </CardContent>
      </Card>

      <Card>
        <CardContent>
          <Paper sx={{ p: 3 }}>
            <Grid container spacing={3}>
              <Grid item xs={12} sm={4}>
                <Typography variant="subtitle2" color="text.secondary">
                  {t("TruckLance Code")}
                </Typography>
                <Typography variant="body1" sx={{ mt: 1 }}>
                  {String(truckData.truckLanceCode || "-")}
                </Typography>
              </Grid>

              <Grid item xs={12} sm={4}>
                <Typography variant="subtitle2" color="text.secondary" sx={{ mb: 1 }}>
                  {t("Departure Time")}
                </Typography>
                {!editingDepartureTime ? (
                  <Stack direction="row" spacing={0.5} alignItems="center" sx={{ mt: 1 }}>
                    <Typography variant="body1">
                      {formatDepartureTime(
                        Array.isArray(truckData.departureTime)
                          ? truckData.departureTime
                          : truckData.departureTime
                            ? String(truckData.departureTime)
                            : null
                      )}
                    </Typography>
                    <IconButton
                      size="small"
                      color="primary"
                      onClick={() => {
                        setDepartureTimeEdit(truckDepartureTimeToInputValue(truckData.departureTime));
                        setEditingDepartureTime(true);
                      }}
                      disabled={savingDepartureTime || saving}
                      title={t("Edit departure time")}
                      aria-label={t("Edit departure time")}
                    >
                      <EditIcon fontSize="small" />
                    </IconButton>
                  </Stack>
                ) : (
                  <Stack direction={{ xs: "column", sm: "row" }} spacing={1} alignItems={{ sm: "flex-start" }}>
                    <TextField
                      type="time"
                      size="small"
                      value={departureTimeEdit}
                      onChange={(e) => setDepartureTimeEdit(e.target.value)}
                      disabled={savingDepartureTime}
                      InputLabelProps={{ shrink: true }}
                      inputProps={{ step: 300 }}
                      sx={{ minWidth: 140 }}
                    />
                    <Stack direction="row" spacing={0.5}>
                      <Button
                        variant="contained"
                        size="small"
                        startIcon={<SaveIcon />}
                        onClick={handleSaveDepartureTimeForAllShops}
                        disabled={
                          savingDepartureTime ||
                          saving ||
                          !truckLanceCode ||
                          !truckData
                        }
                      >
                        {savingDepartureTime ? t("Submitting...") : t("Save")}
                      </Button>
                      <IconButton
                        size="small"
                        color="default"
                        onClick={handleCancelDepartureTimeEdit}
                        disabled={savingDepartureTime}
                        title={t("Cancel editing")}
                        aria-label={t("Cancel editing")}
                      >
                        <CancelIcon />
                      </IconButton>
                    </Stack>
                  </Stack>
                )}
              </Grid>

              <Grid item xs={12} sm={4}>
                <Typography variant="subtitle2" color="text.secondary">
                  {t("Store ID")}
                </Typography>
                <Typography variant="body1" sx={{ mt: 1 }}>
                  {displayStoreId}
                </Typography>
              </Grid>

            </Grid>
          </Paper>
        </CardContent>
      </Card>

      <Card sx={{ mt: 2 }}>
        <CardContent>
          <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", mb: 2 }}>
            <Typography variant="h6">
              {t("Shops Using This Truck Lane")}
            </Typography>
            <Stack direction="row" spacing={1}>
              {massEditing ? (
                <>
                  <Button
                    variant="contained"
                    color="primary"
                    startIcon={<SaveIcon />}
                    onClick={handleSaveMassEdit}
                    disabled={saving}
                  >
                    {saving ? t("Submitting...") : t("Save All")}
                  </Button>
                  <Button
                    variant="outlined"
                    onClick={handleCancelMassEdit}
                    disabled={saving}
                  >
                    {t("Cancel")}
                  </Button>
                </>
              ) : (
                <>
                  <Button
                    variant="outlined"
                    startIcon={<EditIcon />}
                    onClick={handleStartMassEdit}
                    disabled={saving || editingRowIndex !== null || shopsData.length === 0}
                  >
                    {t("Mass Edit")}
                  </Button>
                  <Button
                    variant="contained"
                    startIcon={<AddIcon />}
                    onClick={handleOpenAddShopDialog}
                    disabled={saving || editingRowIndex !== null}
                  >
                    {t("Add Shop")}
                  </Button>
                </>
              )}
            </Stack>
          </Box>
          
          {shopsLoading ? (
            <Box sx={{ display: "flex", justifyContent: "center", p: 4 }}>
              <CircularProgress />
            </Box>
          ) : (
            <TableContainer component={Paper}>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>{t("Shop Name")}</TableCell>
                    <TableCell>{t("Shop Branch")}</TableCell>
                    <TableCell>{t("Shop Code")}</TableCell>
                    <TableCell>{t("Remark")}</TableCell>
                    <TableCell>{t("Loading Sequence")}</TableCell>
                    <TableCell align="right">{t("Actions")}</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {shopsData.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={6} align="center">
                        <Typography variant="body2" color="text.secondary">
                          {t("No shops found using this truck lane")}
                        </Typography>
                      </TableCell>
                    </TableRow>
                  ) : (
                    shopsData.map((shop, index) => (
                      <TableRow key={shop.id ?? `shop-${index}`}>
                        <TableCell>
                          {/* Shop Name from shop table (read-only, looked up by shop code) */}
                          {(() => {
                            const shopCode = String(shop.code || "").trim().toLowerCase();
                            return shopNameByCodeMap.get(shopCode) || "-";
                          })()}
                        </TableCell>
                        <TableCell>{String(shop.name || "-")}</TableCell>
                        <TableCell>{String(shop.code || "-")}</TableCell>
                        <TableCell>
                          {(editingRowIndex === index || massEditing) ? (
                            (() => {
                              const storeIdValue = truckData.storeId ? String(truckData.storeId) : null;
                              const isEditable = normalizeStoreId(storeIdValue) === "4F";
                              return (
                                <Autocomplete
                                  freeSolo
                                  size="small"
                                  options={uniqueRemarks}
                                  value={String(editedShopsData[index]?.remark || "")}
                                  onChange={(_event, newValue) => {
                                    if (isEditable) {
                                      const remarkValue = typeof newValue === 'string' ? newValue : (newValue || "");
                                      handleRemarkChange(index, remarkValue);
                                    }
                                  }}
                                  onInputChange={(_event, newInputValue, reason) => {
                                    if (isEditable && reason === 'input') {
                                      handleRemarkChange(index, newInputValue);
                                    }
                                  }}
                                  disabled={saving || !isEditable}
                                  renderInput={(params) => (
                                    <TextField
                                      {...params}
                                      fullWidth
                                      placeholder={isEditable ? t("Search or select remark") : t("Not editable for this Store ID")}
                                      disabled={saving || !isEditable}
                                    />
                                  )}
                                />
                              );
                            })()
                          ) : (
                            String(shop.remark || "-")
                          )}
                        </TableCell>
                        <TableCell>
                          {(editingRowIndex === index || massEditing) ? (
                            <TextField
                              size="small"
                              type="number"
                              value={(() => {
                                const editedShop = editedShopsData[index];
                                return (editedShop as any)?.LoadingSequence ?? (editedShop as any)?.loadingSequence ?? 0;
                              })()}
                              onChange={(e) => handleLoadingSequenceChange(index, e.target.value)}
                              disabled={saving}
                              sx={{ width: 100 }}
                            />
                          ) : (
                            (() => {
                              const loadingSeq = (shop as any).LoadingSequence ?? (shop as any).loadingSequence;
                              return (loadingSeq !== null && loadingSeq !== undefined)
                                ? String(loadingSeq)
                                : "-";
                            })()
                          )}
                        </TableCell>
                        <TableCell align="right">
                          <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 1 }}>
                            {editingRowIndex === index && !massEditing ? (
                              <>
                                <IconButton
                                  size="small"
                                  color="primary"
                                  onClick={() => handleSave(index)}
                                  disabled={saving}
                                  title={t("Save changes")}
                                >
                                  <SaveIcon />
                                </IconButton>
                                <IconButton
                                  size="small"
                                  color="default"
                                  onClick={() => handleCancel(index)}
                                  disabled={saving}
                                  title={t("Cancel editing")}
                                >
                                  <CancelIcon />
                                </IconButton>
                              </>
                            ) : (
                              <>
                                <IconButton
                                  size="small"
                                  color="primary"
                                  onClick={() => handleEdit(index)}
                                  disabled={massEditing || saving || confirmingDeleteIndex !== null}
                                  title={t("Edit shop details")}
                                >
                                  <EditIcon />
                                </IconButton>
                                {shop.truckId && (
                                  confirmingDeleteIndex === index ? (
                                    <>
                                      <IconButton
                                        size="small"
                                        color="error"
                                        onClick={() => handleDelete(shop.truckId!)}
                                        disabled={saving}
                                        title={t("Confirm delete")}
                                      >
                                        <CheckIcon />
                                      </IconButton>
                                      <IconButton
                                        size="small"
                                        color="default"
                                        onClick={() => setConfirmingDeleteIndex(null)}
                                        disabled={saving}
                                        title={t("Cancel")}
                                      >
                                        <CloseIcon />
                                      </IconButton>
                                    </>
                                  ) : (
                                    <IconButton
                                      size="small"
                                      color="error"
                                      onClick={() => setConfirmingDeleteIndex(index)}
                                      disabled={massEditing || saving || confirmingDeleteIndex !== null}
                                      title={t("Delete truck lane")}
                                    >
                                      <DeleteIcon />
                                    </IconButton>
                                  )
                                )}
                              </>
                            )}
                          </Box>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          )}
        </CardContent>
      </Card>

      {/* Add Shop Dialog */}
      <Dialog open={addShopDialogOpen} onClose={handleCloseAddShopDialog} maxWidth="sm" fullWidth>
        <DialogTitle>{t("Add Shop to Truck Lane")}</DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 2 }}>
            <Grid container spacing={2}>
              <Grid item xs={12}>
                <Autocomplete
                  options={shopTableList}
                  getOptionLabel={(option) => String(option.name || "")}
                  value={
                    shopTableList.find(
                      (s) =>
                        String(s.name || "").trim() === newShop.shopName &&
                        String(s.code || "").trim() === newShop.shopCode
                    ) ?? null
                  }
                  onChange={(_event, newValue) => {
                    handleNewShopNameChange(newValue);
                  }}
                  isOptionEqualToValue={(option, value) =>
                    String(option.code || "").trim() === String(value.code || "").trim()
                  }
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label={t("Shop Name")}
                      fullWidth
                      required
                      disabled={saving}
                      placeholder={t("Search or select shop name")}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  label={t("Loading Sequence")}
                  type="number"
                  fullWidth
                  value={newShop.loadingSequence}
                  onChange={(e) => setNewShop({ ...newShop, loadingSequence: parseInt(e.target.value) || 0 })}
                  disabled={saving}
                />
              </Grid>
              {(() => {
                const storeIdValue = truckData?.storeId ? (typeof truckData.storeId === 'string' || truckData.storeId instanceof String 
                  ? String(truckData.storeId) 
                  : String(truckData.storeId)) : null;
                const isEditable = normalizeStoreId(storeIdValue) === "4F";
                return isEditable ? (
                  <Grid item xs={12}>
                    <Autocomplete
                      freeSolo
                      options={uniqueRemarks}
                      value={newShop.remark || ""}
                      onChange={(event, newValue) => {
                        setNewShop({ ...newShop, remark: typeof newValue === 'string' ? newValue : (newValue || "") });
                      }}
                      onInputChange={(event, newInputValue, reason) => {
                        if (reason === 'input') {
                          setNewShop({ ...newShop, remark: newInputValue });
                        }
                      }}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label={t("Remark")}
                          fullWidth
                          disabled={saving}
                          placeholder={t("Search or select remark")}
                        />
                      )}
                    />
                  </Grid>
                ) : null;
              })()}
            </Grid>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseAddShopDialog} disabled={saving}>
            {t("Cancel")}
          </Button>
          <Button 
            onClick={handleCreateShop} 
            variant="contained" 
            startIcon={<SaveIcon />}
            disabled={saving}
          >
            {saving ? t("Submitting...") : t("Save")}
          </Button>
        </DialogActions>
      </Dialog>

      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
        message={snackbar.message}
      />
    </Box>
  );
};

export default TruckLaneDetail;