// File Path: monorepo/web/frontend/src/pages/Admin/Staff/Add/Step7Page.jsx

import React, { useState, useEffect, useCallback, useMemo, memo } from "react";
import { Link, useNavigate } from "react-router";
import {
  useStaffAddWizardStorage,
  useStaffManager,
} from "../../../../services/Services";
import {
  UserPlusIcon,
  ChevronRightIcon,
  ArrowLeftIcon,
  CheckIcon,
  ChartBarIcon,
  PencilSquareIcon,
  UserIcon,
  MapPinIcon,
  ClipboardDocumentIcon,
  ChartBarSquareIcon,
  CheckCircleIcon,
  UsersIcon,
  InformationCircleIcon,
  PhoneIcon,
  TruckIcon,
  ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { StaffWizardFormStep, UIXThemeProvider, useUIXTheme } from "../../../../components/UIX";
import {
  GENDER_OPTIONS_WITH_EMPTY_OPTION,
  IDENTIFY_AS_OPTIONS,
} from "../../../../constants/FieldOptions";
import {
  STAFF_TYPE_FILTER_OPTIONS,
  STAFF_PHONE_TYPE_OF_OPTIONS_WITH_EMPTY_OPTIONS,
  STAFF_GENDER_OTHER,
} from "../../../../constants/Staff";
import {
  VehicleTypesDisplay,
  TagsDisplay,
} from "../../../../components/business/displays";

// Wizard configuration (static, moved outside component)
const WIZARD_STEPS = [
  { id: 1, title: "Search", subtitle: "Find Staff", isActive: false, isCompleted: true },
  { id: 2, title: "Type", subtitle: "Select Type", isActive: false, isCompleted: true },
  { id: 3, title: "Contact", subtitle: "Information", isActive: false, isCompleted: true },
  { id: 4, title: "Address", subtitle: "Location", isActive: false, isCompleted: true },
  { id: 5, title: "Account", subtitle: "Settings", isActive: false, isCompleted: true },
  { id: 6, title: "Metrics", subtitle: "Performance", isActive: false, isCompleted: true },
  { id: 7, title: "Review", subtitle: "Confirm", isActive: true, isCompleted: false },
];

// DetailField Component for Review Section
const DetailField = ({ label, value, fullWidth = false }) => (
  <div className={fullWidth ? "lg:col-span-2" : ""}>
    <dt className="text-sm sm:text-base font-semibold text-gray-700 mb-2">
      {label}
    </dt>
    <dd className="text-base sm:text-lg font-medium text-gray-900 break-words leading-relaxed">
      {value || <span className="text-gray-400 italic">Not specified</span>}
    </dd>
  </div>
);

// DetailSection Component with UIX Styling
const DetailSection = ({
  title,
  icon: Icon,
  children,
  editLink,
  hasError = false,
  getThemeClasses,
}) => (
  <div
    className={`bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100 hover:shadow-2xl transition-shadow duration-300 mb-6 ${hasError ? `ring-2 ${getThemeClasses('alert-info-border')}` : ""}`}
  >
    {/* Header Section with Theme Gradient */}
    <div className={`px-6 sm:px-8 py-6 border-b border-gray-200 ${getThemeClasses('bg-gradient-secondary')}`}>
      <div className="flex items-center justify-between">
        <h3 className="text-xl sm:text-2xl font-bold text-white flex items-center">
          <Icon className="w-6 sm:w-7 h-6 sm:h-7 mr-3 text-white flex-shrink-0" />
          <span className="truncate">{title}</span>
          {hasError && (
            <ExclamationTriangleIcon className="w-5 sm:w-6 h-5 sm:h-6 ml-3 text-white/80" />
          )}
        </h3>
        {editLink && (
          <Link
            to={editLink}
            className={`inline-flex items-center text-sm font-medium px-3 py-2 rounded-lg transition-colors ${
              hasError
                ? "text-white/80 hover:text-white hover:bg-white/20"
                : "text-white hover:bg-white/20"
            }`}
          >
            <PencilSquareIcon className="w-4 h-4 mr-2" />
            {hasError ? "Fix" : "Edit"}
          </Link>
        )}
      </div>
    </div>

    {/* Content Section */}
    <div className="p-6 sm:p-8">
      <dl className="grid grid-cols-1 lg:grid-cols-2 gap-6 sm:gap-8">
        {children}
      </dl>
    </div>
  </div>
);

// Memoized content component
const Step7Content = memo(function Step7Content() {
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();
  const wizardStorage = useStaffAddWizardStorage();
  const staffManager = useStaffManager();

  // PERFORMANCE: Memoize wizardState to prevent unnecessary re-computation
  const wizardState = useMemo(() => wizardStorage.getWizardState(), [wizardStorage]);

  const [errors, setErrors] = useState({});
  const [fieldErrors, setFieldErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Memoized theme classes
  const themeClasses = useMemo(() => ({
    pageBg: getThemeClasses('page-bg'),
    borderPrimary: getThemeClasses('border-primary'),
    alertInfoBg: getThemeClasses('alert-info-bg'),
    alertInfoBorder: getThemeClasses('alert-info-border'),
    alertInfoText: getThemeClasses('alert-info-text'),
    alertInfoIcon: getThemeClasses('alert-info-icon'),
  }), [getThemeClasses]);

  const onUnauthorized = useCallback(() => {
    navigate("/admin/staff");
  }, [navigate]);

  useEffect(() => {
    window.scrollTo(0, 0);
  }, []);

  // Check for existing state and redirect if needed
  useEffect(() => {
    if (!wizardState || Object.keys(wizardState).length === 0) {
      navigate("/admin/staff/add/step-1-search");
    }
  }, [wizardState, navigate]);


  // Navigation handlers
  const handleBack = useCallback(() => {
    navigate("/admin/staff/add/step-6");
  }, [navigate]);

  const handleCancel = useCallback(() => {
    navigate("/admin/staff");
  }, [navigate]);

  // Map backend field errors to sections for highlighting
  const getSectionWithError = (fieldName) => {
    const contactFields = [
      "email",
      "firstName",
      "lastName",
      "phone",
      "phoneType",
    ];
    const addressFields = [
      "addressLine1",
      "city",
      "region",
      "postalCode",
      "country",
    ];
    const accountFields = [
      "password",
      "passwordRepeated",
      "preferredLanguage",
      "vehicleTypes",
    ];
    const metricsFields = [
      "tags",
      "gender",
      "birthDate",
      "joinDate",
    ];

    if (contactFields.includes(fieldName)) return "contact";
    if (addressFields.includes(fieldName)) return "address";
    if (accountFields.includes(fieldName)) return "account";
    if (metricsFields.includes(fieldName)) return "metrics";

    return null;
  };

  const onSubmitClick = useCallback(async (e) => {
    if (e) e.preventDefault();
    setIsSubmitting(true);
    setErrors({});
    setFieldErrors({});

    try {
      // Prepare the payload
      const payload = { ...wizardState };

      // howDidYouHearAboutUsId - ensure it's properly set from Step 6
      if (!payload.howDidYouHearAboutUsID) {
        // Fallback - should not happen since Step 6 validates this field
        payload.howDidYouHearAboutUsID = "";
      }
      // Map the field name to what the backend expects
      payload.howDidYouHearAboutUsId = payload.howDidYouHearAboutUsID;

      // Fix identifyAs field - convert to array of integers that backend expects
      if (payload.identifyAs && Array.isArray(payload.identifyAs)) {
        // Convert array of objects/strings to array of integers
        payload.identify_as = payload.identifyAs.map(item => {
          if (typeof item === 'object' && item !== null && typeof item.value === 'number') {
            return item.value;
          } else if (typeof item === 'number') {
            return item;
          } else if (typeof item === 'string') {
            return parseInt(item, 10);
          }
          return 0; // fallback
        }).filter(value => !isNaN(value)); // filter out any NaN values

        // Remove the old field name
        delete payload.identifyAs;
      } else if (payload.identifyAs) {
        // If it's not an array, remove the field to avoid backend errors
        delete payload.identifyAs;
      }

      // Handle birthDate - completely remove if empty since backend validation requires string or omission
      if (!payload.birthDate ||
          typeof payload.birthDate !== 'string' ||
          payload.birthDate.trim() === "" ||
          payload.birthDate === "null" ||
          payload.birthDate === "undefined") {
        delete payload.birthDate;
      }

      // Log payload for debugging
      if (import.meta.env.DEV) {
      console.log("=== Staff Creation Payload ===");
      console.log("birthDate in payload:", payload.birthDate);
      }
      if (import.meta.env.DEV) {
      console.log("birthDate type:", typeof payload.birthDate);
      console.log("howDidYouHearAboutUsID (from wizard):", payload.howDidYouHearAboutUsID);
      }
      if (import.meta.env.DEV) {
      console.log("howDidYouHearAboutUsId (for backend):", payload.howDidYouHearAboutUsId);
      console.log("howDidYouHearAboutUsId type:", typeof payload.howDidYouHearAboutUsId);
      }
      if (import.meta.env.DEV) {
      console.log("Payload keys:", Object.keys(payload));
      console.log("Required fields check:");
      console.log("  firstName:", payload.firstName ? "[PRESENT]" : "MISSING");
      console.log("  lastName:", payload.lastName ? "[PRESENT]" : "MISSING");
      console.log("  email:", payload.email ? "[PRESENT]" : "MISSING");
      console.log("  phone:", payload.phone ? "[PRESENT]" : "MISSING");
      console.log("  type:", payload.type);
      console.log("  password:", payload.password ? "[PRESENT]" : "MISSING");
      // SECURITY: Never log PII or password in payload
      }

      // Call the API to create staff
      const response = await staffManager.createStaff(payload, onUnauthorized);

      // Clear wizard state
      wizardStorage.clearWizardState();

      // Navigate to the new staff detail page with success message
      navigate(`/admin/staff/${response.id}`, {
        state: { successMessage: "Staff member created successfully!" },
      });
    } catch (error) {
      if (import.meta.env.DEV) {
      console.error("=== Staff Creation Error ===");
      console.error("Full error object:", error);
      }
      if (import.meta.env.DEV) {
      console.error("Error type:", typeof error);
      console.error("Error keys:", Object.keys(error || {}));
      }
      if (import.meta.env.DEV) {
        console.error("Error details:");
        Object.keys(error || {}).forEach(key => {
          console.error(`  ${key}:`, error[key]);
        });
      }

      // Handle different error formats
      let errorDetails = {};
      let generalError = null;

      if (error && typeof error === "object") {
        // Check for field-specific errors
        const errorFields = Object.keys(error);
        const knownFields = [
          "email",
          "firstName",
          "lastName",
          "phone",
          "phoneType",
          "addressLine1",
          "city",
          "region",
          "postalCode",
          "country",
          "password",
          "passwordRepeated",
          "preferredLanguage",
          "vehicleTypes",
          "tags",
          "gender",
          "birthDate",
          "joinDate",
        ];

        // Extract field errors
        errorFields.forEach((field) => {
          if (knownFields.includes(field)) {
            // Skip birthDate errors since it's optional and we handle it client-side
            if (field === 'birthDate') {
              if (import.meta.env.DEV) {
                console.log("Ignoring birthDate error since it's optional:", error[field]);
              }
              return;
            }
            errorDetails[field] = Array.isArray(error[field])
              ? error[field].join(", ")
              : error[field];
          }
        });

        // Check for general error message
        if (error.message) {
          generalError = error.message;
        } else if (error.detail) {
          generalError = error.detail;
        } else if (error.error) {
          generalError = error.error;
        } else if (Object.keys(errorDetails).length === 0) {
          // If no field errors were found, treat entire error as general
          generalError =
            typeof error === "string"
              ? error
              : "An error occurred while creating the staff member. Please review your information and try again.";
        }
      } else if (typeof error === "string") {
        generalError = error;
      } else {
        generalError = "An unexpected error occurred. Please try again.";
      }

      setFieldErrors(errorDetails);

      // Set general error only if we have one and no field errors
      if (generalError && Object.keys(errorDetails).length === 0) {
        setErrors({ message: generalError });
      } else if (Object.keys(errorDetails).length > 0) {
        // Create a helpful message when there are field errors
        const errorSections = new Set();
        Object.keys(errorDetails).forEach((field) => {
          const section = getSectionWithError(field);
          if (section) errorSections.add(section);
        });

        const sectionNames = {
          contact: "Contact Information",
          address: "Address Information",
          account: "Account Information",
          metrics: "Metrics Information",
        };

        const sectionsWithErrors = Array.from(errorSections)
          .map((s) => sectionNames[s])
          .filter(Boolean);

        const errorMessage =
          sectionsWithErrors.length > 0
            ? `Please fix the errors in the following sections: ${sectionsWithErrors.join(", ")}`
            : "Please fix the validation errors below";

        setErrors({ message: errorMessage });
      }

      window.scrollTo(0, 0);
    } finally {
      setIsSubmitting(false);
    }
  }, [wizardState, staffManager, onUnauthorized, wizardStorage, navigate]);

  // Action configuration
  const actions = useMemo(() => [
    {
      label: "Create Staff Member",
      variant: "success",
      icon: CheckCircleIcon,
      onClick: onSubmitClick,
      disabled: isSubmitting,
      loading: isSubmitting,
    }
  ], [onSubmitClick, isSubmitting]);

  const formatPhoneType = (typeValue) => {
    const option = STAFF_PHONE_TYPE_OF_OPTIONS_WITH_EMPTY_OPTIONS.find(
      (opt) => opt.value === typeValue,
    );
    return option ? option.label : "-";
  };

  const formatGender = (genderValue) => {
    const option = GENDER_OPTIONS_WITH_EMPTY_OPTION.find(
      (opt) => opt.value === genderValue,
    );
    return option ? option.label : "-";
  };

  const formatIdentifyAs = (values) => {
    if (!values || values.length === 0) return "-";
    return values
      .map((val) => {
        const option = IDENTIFY_AS_OPTIONS.find((opt) => opt.value === val);
        return option ? option.label : val;
      })
      .join(", ");
  };

  const formatStaffType = (typeValue) => {
    const option = STAFF_TYPE_FILTER_OPTIONS.find(
      (opt) => opt.value === typeValue,
    );
    return option ? option.label : "-";
  };

  // Helper function to parse array values
  const parseArrayValue = (value) => {
    if (!value) return [];
    if (Array.isArray(value)) return value;
    if (typeof value === "string") {
      return value
        .split(",")
        .map((id) => id.trim())
        .filter(Boolean);
    }
    return [];
  };

  // Check if a section has errors
  const sectionHasErrors = (section) => {
    const fieldsInSection = {
      contact: ["email", "firstName", "lastName", "phone", "phoneType"],
      address: ["addressLine1", "city", "region", "postalCode", "country"],
      shipping: [
        "shippingAddressLine1",
        "shippingCity",
        "shippingRegion",
        "shippingPostalCode",
      ],
      account: [
        "password",
        "passwordRepeated",
        "preferredLanguage",
        "vehicleTypes",
      ],
      metrics: [
        "tags",
        "gender",
        "birthDate",
        "joinDate",
      ],
    };

    return fieldsInSection[section]?.some((field) => fieldErrors[field]);
  };

  return (
    <div className={`min-h-screen ${themeClasses.pageBg} px-4 sm:px-6 lg:px-8`}>
      <div className="max-w-7xl mx-auto py-6 sm:py-8">
        {/* Loading State */}
        {isSubmitting ? (
          <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50">
            <div className="flex items-center">
              <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.borderPrimary}`}></div>
              <span className="ml-3 text-gray-600">Creating staff member...</span>
            </div>
          </div>
        ) : (
          <StaffWizardFormStep
            wizardSteps={WIZARD_STEPS}
            currentStep={7}
            wizardTitle="Add New Staff Member"
            wizardIcon={UserPlusIcon}
            stepTitle="Review & Submit"
            stepSubtitle="Review all information before creating the staff member"
            stepIcon={CheckCircleIcon}
            showFormCard={false}
            contentMaxWidth="7xl"
            errors={errors}
            isLoading={isSubmitting}
            actions={actions}
            onCancel={handleCancel}
            onBack={handleBack}
            actionLayout="end"
          >
            {/* Review Instructions */}
            <div className={`mb-6 ${themeClasses.alertInfoBg} border ${themeClasses.alertInfoBorder} rounded-lg p-4`}>
              <p className={`text-sm ${themeClasses.alertInfoText} flex items-start`}>
                <CheckCircleIcon className="w-5 h-5 mr-2 flex-shrink-0 mt-0.5" />
                <span>
                  Please carefully review the following staff details. If everything
                  looks correct, click the <strong>Create Staff Member</strong> button to complete the process.
                </span>
              </p>
            </div>

            {/* Field Errors Display */}
            {Object.keys(fieldErrors).length > 0 && (
              <div className={`mb-6 ${themeClasses.alertInfoBg} border ${themeClasses.alertInfoBorder} rounded-lg p-4`}>
                <div className="flex items-start">
                  <ExclamationTriangleIcon className={`w-5 h-5 mr-2 flex-shrink-0 mt-0.5 ${themeClasses.alertInfoIcon}`} />
                  <div>
                    <p className={`${themeClasses.alertInfoText} font-semibold`}>Please fix the following errors:</p>
                    <ul className={`mt-2 list-disc list-inside text-sm ${themeClasses.alertInfoText}`}>
                      {Object.entries(fieldErrors).map(([field, error]) => (
                        <li key={field}>
                          <strong>{field}:</strong> {error}
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
              </div>
            )}
          <div>
            {/* Contact Information Section */}
            <DetailSection
              title="Contact Information"
              icon={UserIcon}
              editLink="/admin/staff/add/step-3"
              hasError={sectionHasErrors("contact")}
              getThemeClasses={getThemeClasses}
              customLayout={true}
            >
              {/* Row 1: Type */}
              <div className="lg:col-span-2 mb-4 pb-4 border-b border-gray-200">
                <dt className="text-sm sm:text-base font-semibold text-gray-700 mb-2">Type</dt>
                <dd className="text-base sm:text-lg font-medium text-gray-900 break-words leading-relaxed">
                  {formatStaffType(wizardState.type) || <span className="text-gray-400 italic">Not specified</span>}
                </dd>
                {fieldErrors.type && (
                  <div className={`mt-1 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                    <p className={`${getThemeClasses('alert-info-text')} text-sm`}>{fieldErrors.type}</p>
                  </div>
                )}
              </div>

              {/* Row 2: First Name and Last Name */}
              <div className="lg:col-span-2 mb-4 pb-4 border-b border-gray-200">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                  <div>
                    <DetailField label="First Name" value={wizardState.firstName} />
                    {fieldErrors.firstName && (
                      <div className={`mt-1 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                        <p className={`${getThemeClasses('alert-info-text')} text-sm`}>{fieldErrors.firstName}</p>
                      </div>
                    )}
                  </div>
                  <div>
                    <DetailField label="Last Name" value={wizardState.lastName} />
                    {fieldErrors.lastName && (
                      <div className={`mt-1 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                        <p className={`${getThemeClasses('alert-info-text')} text-sm`}>{fieldErrors.lastName}</p>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Row 3: Email and Phone */}
              <div className="lg:col-span-2 mb-4 pb-4 border-b border-gray-200">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                  <div>
                    <DetailField label="Email" value={wizardState.email} />
                    {fieldErrors.email && (
                      <div className={`mt-1 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                        <p className={`${getThemeClasses('alert-info-text')} text-sm font-semibold`}>
                          <ExclamationTriangleIcon className="inline w-4 h-4 mr-1" />
                          {fieldErrors.email}
                        </p>
                      </div>
                    )}
                  </div>
                  <div>
                    <DetailField
                      label="Phone"
                      value={`${wizardState.phone} (${formatPhoneType(wizardState.phoneType)})`}
                    />
                    {(fieldErrors.phone || fieldErrors.phoneType) && (
                      <div className={`mt-1 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                        <p className={`${getThemeClasses('alert-info-text')} text-sm`}>
                          {fieldErrors.phone || fieldErrors.phoneType}
                        </p>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Row 4: OK to Email */}
              <div className="mb-4">
                <DetailField
                  label="OK to Email"
                  value={wizardState.isOkToEmail ? "Yes" : "No"}
                />
              </div>

              {/* Row 6: OK to Text */}
              <div className="mb-4">
                <DetailField
                  label="OK to Text"
                  value={wizardState.isOkToText ? "Yes" : "No"}
                />
              </div>

              {/* Additional Phone (if provided) */}
              {wizardState.otherPhone && (
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                  <div>
                    <DetailField
                      label="Other Phone"
                      value={`${wizardState.otherPhone} (${formatPhoneType(wizardState.otherPhoneType)})`}
                    />
                  </div>
                </div>
              )}
            </DetailSection>

            {/* Address Information Section */}
            <DetailSection
              title="Address Information"
              icon={MapPinIcon}
              editLink="/admin/staff/add/step-4"
              hasError={sectionHasErrors("address")}
              getThemeClasses={getThemeClasses}
            >
              <DetailField label="Address" value={wizardState.addressLine1} />
              {fieldErrors.addressLine1 && (
                <div className={`lg:col-span-2 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                  <p className={`${getThemeClasses('alert-info-text')} text-sm`}>
                    {fieldErrors.addressLine1}
                  </p>
                </div>
              )}
              {wizardState.addressLine2 && (
                <DetailField
                  label="Address Line 2"
                  value={wizardState.addressLine2}
                />
              )}
              <DetailField label="City" value={wizardState.city} />
              {fieldErrors.city && (
                <div className={`lg:col-span-2 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                  <p className={`${getThemeClasses('alert-info-text')} text-sm`}>{fieldErrors.city}</p>
                </div>
              )}
              <DetailField
                label="Province/Territory"
                value={wizardState.region}
              />
              {fieldErrors.region && (
                <div className={`lg:col-span-2 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                  <p className={`${getThemeClasses('alert-info-text')} text-sm`}>{fieldErrors.region}</p>
                </div>
              )}
              <DetailField label="Postal Code" value={wizardState.postalCode} />
              {fieldErrors.postalCode && (
                <div className={`lg:col-span-2 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                  <p className={`${getThemeClasses('alert-info-text')} text-sm`}>
                    {fieldErrors.postalCode}
                  </p>
                </div>
              )}
              <DetailField label="Country" value={wizardState.country} />
              {fieldErrors.country && (
                <div className={`lg:col-span-2 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                  <p className={`${getThemeClasses('alert-info-text')} text-sm`}>{fieldErrors.country}</p>
                </div>
              )}
            </DetailSection>

            {/* Shipping Address Section (if applicable) */}
            {wizardState.hasShippingAddress && (
              <DetailSection
                title="Shipping Address"
                icon={TruckIcon}
                editLink="/admin/staff/add/step-4"
                hasError={sectionHasErrors("shipping")}
                getThemeClasses={getThemeClasses}
              >
                <DetailField label="Name" value={wizardState.shippingName} />
                <DetailField label="Phone" value={wizardState.shippingPhone} />
                <DetailField
                  label="Address"
                  value={wizardState.shippingAddressLine1}
                />
                {wizardState.shippingAddressLine2 && (
                  <DetailField
                    label="Address Line 2"
                    value={wizardState.shippingAddressLine2}
                  />
                )}
                <DetailField label="City" value={wizardState.shippingCity} />
                <DetailField
                  label="Province/Territory"
                  value={wizardState.shippingRegion}
                />
                <DetailField
                  label="Postal Code"
                  value={wizardState.shippingPostalCode}
                />
                <DetailField
                  label="Country"
                  value={wizardState.shippingCountry}
                />
              </DetailSection>
            )}

            {/* Account Information Section */}
            <DetailSection
              title="Account Information"
              icon={ClipboardDocumentIcon}
              editLink="/admin/staff/add/step-5"
              hasError={sectionHasErrors("account")}
              getThemeClasses={getThemeClasses}
            >
              {fieldErrors.password && (
                <div className={`lg:col-span-2 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                  <p className={`${getThemeClasses('alert-info-text')} text-sm font-semibold`}>
                    <ExclamationTriangleIcon className="inline w-4 h-4 mr-1" />
                    Password: {fieldErrors.password}
                  </p>
                </div>
              )}
              {fieldErrors.passwordRepeated && (
                <div className={`lg:col-span-2 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                  <p className={`${getThemeClasses('alert-info-text')} text-sm font-semibold`}>
                    <ExclamationTriangleIcon className="inline w-4 h-4 mr-1" />
                    Password Confirmation: {fieldErrors.passwordRepeated}
                  </p>
                </div>
              )}

              {wizardState.vehicleTypes &&
                wizardState.vehicleTypes.length > 0 && (
                  <div className="lg:col-span-2 mb-2">
                    <VehicleTypesDisplay
                      values={parseArrayValue(wizardState.vehicleTypes)}
                      label="Vehicle Types"
                      variant="warning"
                      onUnauthorized={onUnauthorized}
                    />
                  </div>
                )}

              {wizardState.limitSpecial && (
                <DetailField
                  label="Limitations/Special Considerations"
                  value={wizardState.limitSpecial}
                  fullWidth
                />
              )}
              {wizardState.policeCheck && (
                <DetailField
                  label="Police Check Expiry"
                  value={wizardState.policeCheck}
                />
              )}
              {wizardState.driversLicenseClass && (
                <DetailField
                  label="Drivers License Class"
                  value={wizardState.driversLicenseClass}
                />
              )}
              <DetailField
                label="Preferred Language"
                value={wizardState.preferredLanguage}
              />
              {fieldErrors.preferredLanguage && (
                <div className={`lg:col-span-2 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('alert-info-border')} rounded p-2`}>
                  <p className={`${getThemeClasses('alert-info-text')} text-sm`}>
                    {fieldErrors.preferredLanguage}
                  </p>
                </div>
              )}

              {/* Emergency Contact */}
              {wizardState.emergencyContactName && (
                <>
                  <DetailField
                    label="Emergency Contact"
                    value={`${wizardState.emergencyContactName} (${wizardState.emergencyContactRelationship})`}
                    fullWidth
                  />
                  <DetailField
                    label="Emergency Phone"
                    value={wizardState.emergencyContactTelephone}
                  />
                  {wizardState.emergencyContactAlternativeTelephone && (
                    <DetailField
                      label="Emergency Alt Phone"
                      value={wizardState.emergencyContactAlternativeTelephone}
                    />
                  )}
                </>
              )}

              {wizardState.description && (
                <DetailField
                  label="Description"
                  value={wizardState.description}
                  fullWidth
                />
              )}
            </DetailSection>

            {/* Metrics Information Section */}
            <DetailSection
              title="Metrics Information"
              icon={ChartBarSquareIcon}
              editLink="/admin/staff/add/step-6"
              hasError={sectionHasErrors("metrics")}
              getThemeClasses={getThemeClasses}
            >
              {wizardState.identifyAs && wizardState.identifyAs.length > 0 && (
                <DetailField
                  label="Identifies As"
                  value={formatIdentifyAs(wizardState.identifyAs)}
                  fullWidth
                />
              )}

              <DetailField
                label="Gender"
                value={formatGender(wizardState.gender)}
              />
              {wizardState.gender === STAFF_GENDER_OTHER &&
                wizardState.genderOther && (
                  <DetailField
                    label="Gender (Other)"
                    value={wizardState.genderOther}
                  />
                )}

              {wizardState.birthDate && (
                <DetailField label="Birth Date" value={wizardState.birthDate} />
              )}

              {wizardState.joinDate && (
                <DetailField label="Join Date" value={wizardState.joinDate} />
              )}


              {/* Tags Display */}
              {wizardState.tags && wizardState.tags.length > 0 && (
                <div className="lg:col-span-2">
                  <TagsDisplay
                    values={parseArrayValue(wizardState.tags)}
                    label="Tags"
                    variant="success"
                    onUnauthorized={onUnauthorized}
                  />
                </div>
              )}

              {wizardState.additionalComment && (
                <DetailField
                  label="Additional Comments"
                  value={wizardState.additionalComment}
                  fullWidth
                />
              )}
            </DetailSection>
          </div>

          </StaffWizardFormStep>
        )}
      </div>
    </div>
  );
});

Step7Content.displayName = 'Step7Content';

function AdminStaffAddStep7Page() {
  return (
    <UIXThemeProvider>
      <Step7Content />
    </UIXThemeProvider>
  );
}

export default AdminStaffAddStep7Page;
