// File Path: monorepo/web/frontend/src/pages/Admin/Event/FieldTrip/Add/Step4Page.jsx

import React from "react";
import { useOffsiteEventWizardStorage } from "../../../../../services/Services";
import { EventStep5Component } from "../../../../../components/business/events";
import {
  TruckIcon,
  CalendarIcon,
  UserGroupIcon,
  MapPinIcon,
} from "@heroicons/react/24/outline";
import { EVENT_TYPE_OFFSITE } from "../../../../../constants/Event";
import { FormSection, InfoField } from "../../../../../components/UIX";
import { formatDateForDisplay } from "../../../../../services/Helpers/DateFormatter";

// Offsite event type configuration
const offsiteConfig = {
  eventType: EVENT_TYPE_OFFSITE,
  labels: {
    wizardTitle: "Add New Field Trip",
    eventTypeName: "Field Trip",
    backToList: "Back to Field Trips",
  },
  icons: {
    wizard: TruckIcon,
  },
  routes: {
    list: "/admin/events/field-trips",
    step1: "/admin/events/field-trips/add/step-1",
    step2: "/admin/events/field-trips/add/step-2",
    step3: "/admin/events/field-trips/add/step-3",
    step4: "/admin/events/field-trips/add/step-4",
  },
};

// Wrapper for Offsite storage to match the generic interface
const createOffsiteStorageWrapper = (offsiteEventWizardStorage) => ({
  getWizardData: () => offsiteEventWizardStorage.getOffsiteEventWizard(),
  saveWizardData: (data) =>
    offsiteEventWizardStorage.saveOffsiteEventWizard(data),
  clearWizardData: () => offsiteEventWizardStorage.clearOffsiteEventWizard(),
});

// Offsite-specific review sections
const offsiteCustomReviewSections = (wizardData, onUnauthorized) => {
  // Guard against null wizardData (can happen after successful submission during navigation delay)
  if (!wizardData) return null;

  return (
    <>
      {/* Destination Information Section */}
      <FormSection
        title="Field Trip Destination"
        description="Where the field trip will take place"
        className="mb-6"
      >
        <div className="grid grid-cols-1 gap-4 sm:gap-6">
          {wizardData.destinationName && (
            <InfoField
              label="Destination Name"
              value={wizardData.destinationName}
              icon={MapPinIcon}
            />
          )}
          {wizardData.destinationAddress && (
            <InfoField
              label="Destination Address"
              value={`${wizardData.destinationAddress}, ${wizardData.destinationCity}, ${wizardData.destinationProvince} ${wizardData.destinationPostalCode}, ${wizardData.destinationCountry}`}
            />
          )}
        </div>
      </FormSection>

      {/* Transportation Information Section */}
      {(wizardData.departureLocation ||
        wizardData.travelTime ||
        wizardData.transportationNotes) && (
        <FormSection
          title="Transportation Details"
          description="Travel logistics and departure information"
          className="mb-6"
        >
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
            {wizardData.departureLocation && (
              <InfoField
                label="Departure Location"
                value={wizardData.departureLocation}
              />
            )}
            {wizardData.travelTime && (
              <InfoField
                label="Travel Time"
                value={`${wizardData.travelTime} minutes`}
              />
            )}
          </div>
          {wizardData.transportationNotes && (
            <div className="mt-4">
              <InfoField
                label="Transportation Notes"
                value={wizardData.transportationNotes}
              />
            </div>
          )}
        </FormSection>
      )}

      {/* Schedule Details */}
      <FormSection
        title="Schedule Information"
        description="Event date and time details"
        className="mb-6"
      >
        <InfoField
          label="Event Schedule"
          value={
            wizardData.startDate && wizardData.endDate
              ? `${formatDateForDisplay(wizardData.startDate)} - ${formatDateForDisplay(wizardData.endDate)}`
              : wizardData.date && wizardData.startTime && wizardData.endTime
                ? `${wizardData.date} from ${wizardData.startTime} to ${wizardData.endTime}`
                : "Not specified"
          }
          icon={CalendarIcon}
        />
        {wizardData.attendeeCapacity && (
          <InfoField
            label="Expected Students"
            value={`${wizardData.attendeeCapacity} students`}
            icon={UserGroupIcon}
          />
        )}
      </FormSection>
    </>
  );
};

// Offsite-specific payload processing
const offsiteCustomPayloadProcessing = (payload, wizardData) => {
  // Build destination address from components (legacy fields)
  const destinationComponents = [
    wizardData.destinationAddress,
    wizardData.destinationCity,
    wizardData.destinationProvince,
    wizardData.destinationPostalCode,
    wizardData.destinationCountry,
  ].filter(Boolean);

  const fullDestinationAddress =
    destinationComponents.length > 0
      ? destinationComponents.join(", ")
      : wizardData.destinationName || "";

  return {
    ...payload,
    // Offsite-specific fields
    // Use fullDestinationAddress if available (legacy), otherwise keep the location from Step 2
    location:
      fullDestinationAddress || payload.location || wizardData.location || "",
    dayOfWeek: wizardData.dayOfWeek || "Monday",
    // isSHSM is now a boolean - convert legacy int values if needed
    isSHSM:
      wizardData.isSHSM === true || wizardData.isSHSM === 1
        ? true
        : wizardData.isSHSM === false || wizardData.isSHSM === 2
          ? false
          : null,
    facilitatorAM: wizardData.facilitatorAM || false,
    facilitatorPM: wizardData.facilitatorPM || false,
    eventType: EVENT_TYPE_OFFSITE, // Always set to Offsite type
    attendeeCapacity: parseInt(wizardData.attendeeCapacity) || 0,
    // Offsite-specific destination fields
    destinationName: wizardData.destinationName || "",
    destinationAddress: wizardData.destinationAddress || "",
    destinationCity: wizardData.destinationCity || "",
    destinationProvince: wizardData.destinationProvince || "",
    destinationPostalCode: wizardData.destinationPostalCode || "",
    destinationCountry: wizardData.destinationCountry || "",
    departureLocation: wizardData.departureLocation || "",
    travelTime: parseInt(wizardData.travelTime) || 0,
    transportationNotes: wizardData.transportationNotes || "",
  };
};

function AdminEventFieldTripAddStep5Page() {
  const offsiteEventWizardStorage = useOffsiteEventWizardStorage();
  const wrappedStorage = createOffsiteStorageWrapper(offsiteEventWizardStorage);

  return (
    <EventStep5Component
      wizardStorage={wrappedStorage}
      eventTypeConfig={offsiteConfig}
      customReviewSections={offsiteCustomReviewSections}
      customPayloadProcessing={offsiteCustomPayloadProcessing}
    />
  );
}

export default AdminEventFieldTripAddStep5Page;
