import type { BookerInfo, PassengerInfo } from "@/components/booking/booking-types";
import { parseDisplayDate } from "@/lib/booking-search";

export type FieldErrors = Record<string, string>;

export function validateBookerStep(booker: BookerInfo): FieldErrors {
  const errors: FieldErrors = {};
  if (!booker.fullName.trim()) {
    errors["booker-name"] = "Vui lòng nhập tên người đặt vé";
  }
  if (!booker.phone.trim()) {
    errors["booker-phone"] = "Vui lòng nhập số điện thoại/Zalo";
  }
  return errors;
}

export function validatePassengersStep(
  passengers: PassengerInfo[],
  options?: { tripDepartDate?: string },
): FieldErrors {
  const errors: FieldErrors = {};
  const tripDate = options?.tripDepartDate ? parseDisplayDate(options.tripDepartDate) : null;

  passengers.forEach((p, index) => {
    if (!p.fullName.trim()) {
      errors[`p-name-${index}`] = "Vui lòng nhập họ và tên";
    }
    if (!p.birthDate.trim()) {
      errors[`p-birth-${index}`] = "Vui lòng chọn ngày tháng năm sinh";
    } else {
      const birth = parseDisplayDate(p.birthDate);
      if (!birth) {
        errors[`p-birth-${index}`] = "Ngày sinh không hợp lệ";
      } else if (tripDate && birth > tripDate) {
        errors[`p-birth-${index}`] = "Ngày sinh phải trước hoặc trùng ngày đi tàu";
      }
    }
    if (!p.idNumber.trim()) {
      errors[`p-id-${index}`] = "Vui lòng nhập số CCCD";
    }
    if (!p.nationality.trim()) {
      errors[`p-nat-${index}`] = "Vui lòng chọn quốc tịch";
    }
    if (!p.hometown.trim()) {
      errors[`p-home-${index}`] = "Vui lòng nhập quê quán";
    }
  });
  return errors;
}

export function clearFieldError(errors: FieldErrors, fieldId: string): FieldErrors {
  if (!errors[fieldId]) return errors;
  const next = { ...errors };
  delete next[fieldId];
  return next;
}
