"use client";

import { useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import { useCartSessionId } from "@/lib/cart/useCartSessionId";
import { useCartValidation, useShippingAddresses } from "@/lib/checkout";
import type { CheckoutStep } from "@/lib/checkout/constants";
import type { CheckoutSelectedShippingRate } from "@/lib/checkout/types";
import { CheckoutShell } from "@/components/checkout/CheckoutShell";
import { CartValidationStep } from "@/components/checkout/steps/CartValidationStep";
import { ShippingAddressStep } from "@/components/checkout/steps/ShippingAddressStep";
import { OrderReviewStep } from "@/components/checkout/steps/OrderReviewStep";
import { PaymentStep } from "@/components/checkout/steps/PaymentStep";
import { CheckoutSkeleton } from "@/components/checkout/state/CheckoutSkeleton";
import { CheckoutErrorState } from "@/components/checkout/state/CheckoutErrorState";

export function CheckoutPageView() {
  const sessionId = useCartSessionId();
  const { result, isLoading } = useCartValidation(sessionId);
  const { addresses, isLoading: isLoadingAddresses } = useShippingAddresses();
  const router = useRouter();

  const [currentStep, setCurrentStep] = useState<CheckoutStep>("validation");
  const [selectedAddressId, setSelectedAddressId] = useState<string | null>(null);
  const [shipmentObjectId, setShipmentObjectId] = useState<string | null>(null);
  const [selectedShippingRate, setSelectedShippingRate] = useState<CheckoutSelectedShippingRate | null>(null);

  const isEmpty = !isLoading && result !== null && result.items.length === 0;

  useEffect(() => {
    if (isEmpty) router.replace("/cart");
  }, [isEmpty, router]);

  if (isLoading) {
    return (
      <CheckoutShell currentStep="validation">
        <CheckoutSkeleton />
      </CheckoutShell>
    );
  }

  if (!result) {
    return (
      <CheckoutShell currentStep="validation">
        <CheckoutErrorState
          message="Something went wrong loading your checkout."
          onRetry={() => window.location.reload()}
        />
      </CheckoutShell>
    );
  }

  if (result.items.length === 0) return null;

  return (
    <CheckoutShell currentStep={currentStep}>
      {currentStep === "validation" && (
        <CartValidationStep
          result={result}
          onProceed={() => setCurrentStep("shipping-address")}
          onBackToCart={() => router.push("/cart")}
        />
      )}

      {currentStep === "shipping-address" && (
        <ShippingAddressStep
          addresses={addresses}
          isLoadingAddresses={isLoadingAddresses}
          onProceed={(addressId) => {
            setSelectedAddressId(addressId);
            setCurrentStep("review");
          }}
          onBack={() => setCurrentStep("validation")}
        />
      )}

      {currentStep === "review" && selectedAddressId && result && (
        <OrderReviewStep
          addressId={selectedAddressId}
          addresses={addresses}
          cartResult={result}
          sessionId={sessionId}
          onProceed={(shipmentId, shippingRate) => {
            setShipmentObjectId(shipmentId);
            setSelectedShippingRate(shippingRate);
            setCurrentStep("payment");
          }}
          onBack={() => setCurrentStep("shipping-address")}
        />
      )}

      {currentStep === "payment" &&
        selectedAddressId &&
        shipmentObjectId &&
        selectedShippingRate && (
          <PaymentStep
            shipmentObjectId={shipmentObjectId}
            selectedShippingRate={selectedShippingRate}
            addressId={selectedAddressId}
            sessionId={sessionId}
            onBack={() => setCurrentStep("review")}
          />
        )}
    </CheckoutShell>
  );
}
