import { customers } from "../customers/customers.mock";

export type BookingStatus =
  | "Pending"
  | "Confirmed"
  | "In Transit"
  | "Delivered"
  | "Cancelled";

export type CargoType =
  | "Containerized"
  | "Bulk"
  | "Liquid"
  | "Refrigerated"
  | "Hazardous";

export type TransportMode = "Rail" | "Truck" | "Multimodal";

export type LegMode = "Rail" | "Truck";

export type ContainerType = "20FT" | "40FT" | "40HC" | "Reefer";

export type Priority = "Normal" | "High" | "Urgent";

export interface TransportLeg {
  mode: LegMode;
  from: string;
  to: string;
}

export interface Booking {
  id: number;
  reference: string;
  customerId: number;
  customer: string;
  cargoType: CargoType;
  originStation: string;
  destinationStation: string;
  transportMode: TransportMode;
  legs?: TransportLeg[];
  containerType: ContainerType;
  containerCount: number;
  weightTons: number;
  requestedDate: string;
  priority: Priority;
  cargoDescription: string;
  specialInstructions: string;
  status: BookingStatus;
}

const stations = [
  "Addis Ababa",
  "Adama",
  "Mojo",
  "Awash",
  "Mieso",
  "Dire Dawa",
  "Aysha",
  "Ali Sabieh",
  "Holhol",
  "Djibouti City",
];

const cargoTypes: CargoType[] = [
  "Containerized",
  "Bulk",
  "Liquid",
  "Refrigerated",
  "Hazardous",
];
const modes: TransportMode[] = ["Rail", "Truck", "Multimodal"];
const containerTypes: ContainerType[] = ["20FT", "40FT", "40HC", "Reefer"];
const statuses: BookingStatus[] = [
  "Pending",
  "Confirmed",
  "In Transit",
  "Delivered",
  "Cancelled",
];
const priorities: Priority[] = ["Normal", "High", "Urgent"];

function pickStation(i: number, offset: number) {
  return stations[(i + offset) % stations.length] as string;
}

const INITIAL_BOOKINGS: Booking[] = Array.from({ length: 22 }, (_, i) => {
  const customer = customers[i % customers.length] as (typeof customers)[number];
  const id = i + 1;
  const requested = new Date(2026, 4, 1 + (i % 28));
  const transportMode = modes[i % modes.length] as TransportMode;
  const originStation = pickStation(i, 0);
  const destinationStation = pickStation(i, 5);
  const midStation = pickStation(i, 3);
  const legs: TransportLeg[] | undefined =
    transportMode === "Multimodal"
      ? [
          { mode: "Rail", from: originStation, to: midStation },
          { mode: "Truck", from: midStation, to: destinationStation },
        ]
      : undefined;
  return {
    id,
    reference: `BK-${String(2026000 + id).slice(-6)}`,
    customerId: customer.id,
    customer: customer.company,
    cargoType: cargoTypes[i % cargoTypes.length] as CargoType,
    originStation,
    destinationStation,
    transportMode,
    legs,
    containerType: containerTypes[i % containerTypes.length] as ContainerType,
    containerCount: (i % 5) + 1,
    weightTons: 10 + ((i * 3) % 40),
    requestedDate: requested.toISOString().slice(0, 10),
    priority: priorities[i % priorities.length] as Priority,
    cargoDescription:
      i % 3 === 0
        ? "Coffee beans, sealed sacks"
        : i % 3 === 1
        ? "Construction materials"
        : "General merchandise",
    specialInstructions:
      i % 2 === 0 ? "Handle with care" : "Standard handling required",
    status: statuses[i % statuses.length] as BookingStatus,
  };
});

const getStoredBookings = (): Booking[] => {
  if (typeof window === "undefined" || !window.localStorage) {
    return INITIAL_BOOKINGS;
  }
  const data = localStorage.getItem("edr_bookings");
  if (!data) {
    localStorage.setItem("edr_bookings", JSON.stringify(INITIAL_BOOKINGS));
    return INITIAL_BOOKINGS;
  }
  try {
    return JSON.parse(data);
  } catch (e) {
    return INITIAL_BOOKINGS;
  }
};

export const bookings: Booking[] = getStoredBookings();

export function saveBookingsToStorage() {
  if (typeof window !== "undefined" && window.localStorage) {
    localStorage.setItem("edr_bookings", JSON.stringify(bookings));
  }
}

export function addBooking(booking: Booking) {
  bookings.unshift(booking);
  saveBookingsToStorage();
}

export function deleteBooking(id: number) {
  const index = bookings.findIndex((b) => b.id === id);
  if (index !== -1) {
    bookings.splice(index, 1);
    saveBookingsToStorage();
  }
}

export function getBookingById(id: number | string): Booking | undefined {
  const numericId = typeof id === "string" ? Number(id) : id;
  return bookings.find((b) => b.id === numericId);
}
