"use client";

import { useMemo } from "react";
import { RESIDENCE_TYPE, type ResidenceType } from "@customer-portal/domain/address";
import { isValidStreetAddress } from "@/features/address/utils";

interface AddressState {
  postcode: string;
  prefecture: string;
  city: string;
  town: string;
  streetAddress: string;
  buildingName?: string | null | undefined;
  roomNumber?: string | null | undefined;
  residenceType: ResidenceType | "";
}

interface UseAddressCompletionOptions {
  /** Current address state */
  address: AddressState;
  /** Whether the address has been verified via ZIP lookup */
  isAddressVerified: boolean;
}

/**
 * Hook that calculates address completion state.
 * Returns flags for each completion condition and the current step.
 */
export function useAddressCompletion({ address, isAddressVerified }: UseAddressCompletionOptions) {
  return useMemo(() => {
    // Has valid residence type selected
    const hasResidenceType =
      address.residenceType === RESIDENCE_TYPE.HOUSE ||
      address.residenceType === RESIDENCE_TYPE.APARTMENT;

    // All base fields are filled
    const baseFieldsFilled =
      address.postcode.trim() !== "" &&
      address.prefecture.trim() !== "" &&
      address.city.trim() !== "" &&
      address.town.trim() !== "" &&
      isValidStreetAddress(address.streetAddress);

    // Room number is OK (not required for houses, required for apartments)
    const roomNumberOk =
      address.residenceType !== RESIDENCE_TYPE.APARTMENT ||
      (address.roomNumber?.trim() ?? "") !== "";

    // Building name is required for both houses and apartments
    const buildingNameOk = (address.buildingName?.trim() ?? "") !== "";

    // Overall completion
    const isComplete =
      isAddressVerified && hasResidenceType && baseFieldsFilled && buildingNameOk && roomNumberOk;

    // Calculate current step (0-4)
    const getCurrentStep = (): number => {
      if (!isAddressVerified) return 0;
      if (!address.streetAddress.trim()) return 1;
      if (!address.residenceType) return 2;
      if (address.residenceType === RESIDENCE_TYPE.APARTMENT && !address.roomNumber?.trim())
        return 3;
      return 4;
    };

    return {
      /** Whether all fields are complete */
      isComplete,
      /** Whether a valid residence type is selected */
      hasResidenceType,
      /** Whether all base fields (postcode, prefecture, city, town, street) are filled */
      baseFieldsFilled,
      /** Whether room number requirement is satisfied */
      roomNumberOk,
      /** Whether building name is filled */
      buildingNameOk,
      /** Current step in the form (0-4) */
      currentStep: getCurrentStep(),
    };
  }, [address, isAddressVerified]);
}
