import type { TruckLaneScheduleLineResponse } from "@/app/api/shop/actions";
import type { ScheduleLaneOption } from "@/components/Shop/ScheduleChangeModal";
import { toDistrictDisplayName } from "@/components/Shop/routeBoardDisplayOrder";
import { formatScheduleTargetLaneLabel } from "@/components/Shop/scheduleRouteExcelToMoves";

export function resolveScheduleLaneLabel(
  line: TruckLaneScheduleLineResponse,
  kind: "from" | "to",
  laneById?: Map<string, ScheduleLaneOption>,
): string {
  const code =
    kind === "from" ? line.fromTruckLanceCode : line.toTruckLanceCode;
  const remark = kind === "from" ? line.fromRemark : line.toRemark;
  const storeId = kind === "from" ? line.fromStoreId : line.toStoreId;
  if (!code?.trim()) return "—";
  if (laneById) {
    const match = Array.from(laneById.values()).find(
      (l) =>
        l.truckLanceCode === code &&
        (l.remark ?? "") === (remark ?? "") &&
        l.storeId === storeId,
    );
    if (match) return match.label;
  }
  return formatScheduleTargetLaneLabel(code, remark);
}

export function isSameScheduleLaneBucket(
  line: TruckLaneScheduleLineResponse,
): boolean {
  const norm = (v?: string | null) => (v ?? "").trim();
  return (
    norm(line.fromTruckLanceCode) === norm(line.toTruckLanceCode) &&
    norm(line.fromRemark) === norm(line.toRemark) &&
    norm(line.fromStoreId) === norm(line.toStoreId)
  );
}

function normDistrict(v?: string | null): string {
  return toDistrictDisplayName(v ?? null) || "—";
}

function formatTimeLabel(v?: string | null): string | null {
  const raw = v?.trim();
  if (!raw) return null;
  const tIdx = raw.indexOf("T");
  if (tIdx >= 0) return raw.slice(tIdx + 1, tIdx + 6);
  return raw.length >= 5 ? raw.slice(0, 5) : raw;
}

function formatSeqValue(from?: number | null, to?: number | null): string | null {
  if (from != null && to != null && from !== to) return `${from} → ${to}`;
  if (to != null) return String(to);
  if (from != null) return String(from);
  return null;
}

export type ScheduleLineDescription = {
  headline: string;
  details: string[];
};

type TranslateFn = (key: string, opts?: Record<string, unknown>) => string;

export function buildScheduleLineDescription(
  line: TruckLaneScheduleLineResponse,
  laneById: Map<string, ScheduleLaneOption> | undefined,
  t: TranslateFn,
): ScheduleLineDescription {
  const toLane = resolveScheduleLaneLabel(line, "to", laneById);
  const fromLane = resolveScheduleLaneLabel(line, "from", laneById);
  const details: string[] = [];

  const pushSeq = () => {
    const seq = formatSeqValue(line.fromLoadingSequence, line.toLoadingSequence);
    if (seq) details.push(t("schedule_line_seq", { value: seq }));
  };

  const pushDistrict = () => {
    const fromDist = normDistrict(line.fromDistrictReference);
    const toDist = normDistrict(line.toDistrictReference);
    if (fromDist !== toDist) {
      details.push(
        t("schedule_line_district_change", { from: fromDist, to: toDist }),
      );
    } else if (line.action === "CREATE" && toDist !== "—") {
      details.push(t("schedule_line_district_target", { district: toDist }));
    }
  };

  const pushDeparture = () => {
    const fromDep = formatTimeLabel(line.fromDepartureTime);
    const toDep = formatTimeLabel(line.departureTime);
    if (fromDep && toDep && fromDep !== toDep) {
      details.push(
        t("schedule_line_departure_change", { from: fromDep, to: toDep }),
      );
    } else if (toDep && line.action === "CREATE") {
      details.push(t("schedule_line_departure_target", { time: toDep }));
    }
  };

  switch (line.action) {
    case "DELETE":
      return {
        headline: t("schedule_line_remove_from", {
          lane: fromLane !== "—" ? fromLane : toLane,
        }),
        details,
      };
    case "ENSURE_LANE":
      pushDeparture();
      return {
        headline: t("schedule_line_ensure_lane", { lane: toLane }),
        details,
      };
    case "CREATE":
      pushSeq();
      pushDistrict();
      pushDeparture();
      return {
        headline: t("schedule_line_add_to", { lane: toLane }),
        details,
      };
    case "MOVE":
    default: {
      if (isSameScheduleLaneBucket(line)) {
        pushSeq();
        pushDistrict();
        pushDeparture();
        return {
          headline: t("schedule_line_on_lane", { lane: toLane }),
          details,
        };
      }
      pushSeq();
      pushDistrict();
      pushDeparture();
      return {
        headline: t("schedule_line_lane_change", { from: fromLane, to: toLane }),
        details,
      };
    }
  }
}
