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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import {
  useAuthManager,
  useSpeakerManager,
} from "../../../../services/Services";
import {
  ChatBubbleBottomCenterIcon,
  ArrowLeftIcon,
  CheckCircleIcon,
  UserIcon,
  MapPinIcon,
  HomeIcon,
  TruckIcon,
  ClipboardDocumentIcon,
  ChartBarSquareIcon,
  PencilSquareIcon,
  CheckIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import {
  UIXThemeProvider,
  StepWizard,
  FormCard,
  Button,
  Alert,
} from "../../../../components/UIX";
import {
  HowHearAboutUsDisplay,
  VehicleTypesDisplay,
  TagsDisplay,
  SkillSetsDisplay,
  ServiceFeeDisplay,
  InsuranceRequirementsDisplay,
} from "../../../../components/business/displays";
import {
  SPEAKER_IS_JOB_SEEKER_YES,
  SPEAKER_GENDER_OTHER,
} from "../../../../constants/Speaker";

const REPRESENTATIVE_SPEAKER_TYPE_OF_ID = 2;
const SPEAKER_PHONE_TYPE_WORK = 2;

// Wizard steps configuration
const WIZARD_STEPS = [
  { title: "Search", isCompleted: true },
  { title: "Type", isCompleted: true },
  { title: "Contact", isCompleted: true },
  { title: "Address", isCompleted: true },
  { title: "Account", isCompleted: true },
  { title: "Metrics", isCompleted: true },
  { title: "Review", isCompleted: false },
];

function AdminSpeakerAddStep7Page() {
  const authManager = useAuthManager();
  const speakerManager = useSpeakerManager();
  const navigate = useNavigate();

  const [errors, setErrors] = useState({});
  const [fieldErrors, setFieldErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [speakerData, setSpeakerData] = useState(null);

  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }
    loadSpeakerState();
  }, [authManager, navigate]);

  const loadSpeakerState = useCallback(() => {
    try {
      const existing = sessionStorage.getItem("FLASHPOINTTRAINING_SPEAKER_CREATION_STATE");
      if (existing) {
        const speakerState = JSON.parse(existing);
        setSpeakerData(speakerState);
      } else {
        navigate("/admin/speakers/add/step-1-search");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error loading speaker state:", error);
      }
      navigate("/admin/speakers/add/step-1-search");
    }
  }, [navigate]);

  const getSectionWithError = useCallback((fieldName) => {
    const contactFields = ["email", "firstName", "lastName", "phone", "phoneType", "representitiveOrganizationName", "representitiveOrganizationType"];
    const addressFields = ["addressLine1", "city", "region", "postalCode", "country"];
    const shippingFields = ["shippingAddressLine1", "shippingCity", "shippingRegion", "shippingPostalCode", "shippingCountry", "shippingName", "shippingPhone"];
    const accountFields = ["level", "availability", "skillSets", "insuranceRequirements", "vehicleTypes", "serviceFeeId", "hourlySalaryDesired", "duesDate", "policeCheck", "preferredLanguage"];
    const metricsFields = ["tags", "howDidYouHearAboutUsID", "gender", "birthDate", "joinDate", "isJobSeeker", "statusInCountry", "maritalStatus", "accomplishedEducation"];

    if (contactFields.includes(fieldName)) return "contact";
    if (addressFields.includes(fieldName)) return "address";
    if (shippingFields.includes(fieldName)) return "shipping";
    if (accountFields.includes(fieldName)) return "account";
    if (metricsFields.includes(fieldName)) return "metrics";
    return null;
  }, []);

  const sectionHasErrors = useCallback((section) => {
    const fieldsInSection = {
      contact: ["email", "firstName", "lastName", "phone", "phoneType", "representitiveOrganizationName", "representitiveOrganizationType"],
      address: ["addressLine1", "city", "region", "postalCode", "country"],
      shipping: ["shippingAddressLine1", "shippingCity", "shippingRegion", "shippingPostalCode", "shippingCountry", "shippingName", "shippingPhone"],
      account: ["level", "availability", "skillSets", "insuranceRequirements", "vehicleTypes", "serviceFeeId", "hourlySalaryDesired", "duesDate", "policeCheck", "preferredLanguage"],
      metrics: ["tags", "howDidYouHearAboutUsID", "gender", "birthDate", "joinDate", "isJobSeeker", "statusInCountry", "maritalStatus", "accomplishedEducation"],
    };
    return fieldsInSection[section]?.some((field) => fieldErrors[field]);
  }, [fieldErrors]);

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

    try {
      if (!speakerData) {
        throw new Error("No speaker data found");
      }

      const processedData = processSpeakerData(speakerData);
      const response = await speakerManager.createSpeaker(processedData, () => navigate("/login?unauthorized=true"));

      sessionStorage.removeItem("FLASHPOINTTRAINING_SPEAKER_CREATION_STATE");
      navigate(`/admin/speaker/${response.id}`, {
        state: { successMessage: "Speaker created successfully!" },
      });
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Failed to create speaker:", error);
      }

      let errorDetails = {};
      let generalError = null;

      if (error && typeof error === "object") {
        const knownFields = ["email", "firstName", "lastName", "phone", "phoneType", "addressLine1", "city", "region", "postalCode", "country", "shippingAddressLine1", "shippingCity", "shippingRegion", "shippingPostalCode", "shippingCountry", "shippingName", "shippingPhone", "skillSets", "insuranceRequirements", "vehicleTypes", "serviceFeeId", "hourlySalaryDesired", "duesDate", "policeCheck", "preferredLanguage", "tags", "howDidYouHearAboutUsID", "gender", "birthDate", "joinDate", "isJobSeeker", "representitiveOrganizationName", "representitiveOrganizationType", "level", "availability"];

        Object.keys(error).forEach((field) => {
          if (knownFields.includes(field)) {
            errorDetails[field] = Array.isArray(error[field]) ? error[field].join(", ") : error[field];
          }
        });

        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) {
          generalError = typeof error === "string" ? error : "An error occurred while creating the speaker. 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);

      if (generalError && Object.keys(errorDetails).length === 0) {
        setErrors({ general: generalError });
      } else if (Object.keys(errorDetails).length > 0) {
        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",
          shipping: "Shipping Address",
          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({ general: errorMessage });
      }

      window.scrollTo(0, 0);
    } finally {
      setIsLoading(false);
    }
  }, [speakerData, speakerManager, navigate, getSectionWithError]);

  const processSpeakerData = (data) => {
    const processed = { ...data };

    // Remove fields that are no longer collected
    delete processed.identifyAs;
    delete processed.howDidYouHearAboutUsID;
    delete processed.isHowDidYouHearAboutUsOther;
    delete processed.howDidYouHearAboutUsOther;
    delete processed.commercialInsuranceExpiryDate;
    delete processed.certifications;
    delete processed.specializations;

    // Date conversions
    const dateFields = ["duesDate", "policeCheck", "birthDate", "joinDate", "autoInsuranceExpiryDate", "wsibInsuranceDate", "dateOfEntryIntoCountry"];
    dateFields.forEach((field) => {
      if (processed[field] && !processed[field].includes("T")) {
        processed[field] = new Date(processed[field]).toISOString();
      }
    });

    // Array conversions
    const arrayFields = ["skillSets", "insuranceRequirements", "vehicleTypes", "tags"];
    arrayFields.forEach((field) => {
      if (typeof processed[field] === "string") {
        processed[field] = processed[field].split(",").map((id) => id.trim()).filter(Boolean);
      }
    });

    // Numeric conversions
    if (processed.hourlySalaryDesired) processed.hourlySalaryDesired = parseInt(processed.hourlySalaryDesired);

    const intFields = ["statusInCountry", "maritalStatus", "accomplishedEducation", "gender", "type", "representitiveOrganizationType", "phoneType", "otherPhoneType", "isJobSeeker"];
    intFields.forEach((field) => {
      if (processed[field] !== undefined && processed[field] !== "" && processed[field] !== 0) {
        processed[field] = parseInt(processed[field]);
      }
    });

    // Clean up empty values
    Object.keys(processed).forEach((key) => {
      if (processed[key] === "" || processed[key] === null || processed[key] === undefined) {
        delete processed[key];
      }
    });

    return processed;
  };

  const getPhoneTypeLabel = (phoneType) => {
    switch (phoneType) {
      case 1: return "Mobile";
      case 2: return "Work";
      case 3: return "Home";
      default: return "Unknown";
    }
  };

  const getOrganizationTypeLabel = (organizationType) => {
    switch (organizationType) {
      case 1: return "Educational";
      case 2: return "Private/Corporate";
      case 3: return "Non-profit";
      case 4: return "Government";
      default: return "Unknown";
    }
  };

  const getGenderLabel = (gender) => {
    switch (gender) {
      case 1: return "Other";
      case 2: return "Male";
      case 3: return "Female";
      default: return "Unknown";
    }
  };

  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 [];
  };

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

  if (!speakerData) {
    return (
      <UIXThemeProvider>
        <div className="min-h-screen flex items-center justify-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-current opacity-25"></div>
        </div>
      </UIXThemeProvider>
    );
  }

  const ReviewField = ({ label, value, error }) => (
    <div>
      <span className="block text-lg font-medium opacity-70 mb-2">{label}</span>
      <p className="text-xl opacity-90">{value || "—"}</p>
      {error && (
        <p className="mt-2 text-lg text-red-600 bg-red-50 p-3 rounded">{error}</p>
      )}
    </div>
  );

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={7}
        title="Add New Speaker"
        subtitle="Review and submit the new speaker information"
        icon={ChatBubbleBottomCenterIcon}
      >
        {/* Error Alert */}
        {errors.general && (
          <Alert
            type="error"
            message={errors.general}
            onClose={() => { setErrors({}); setFieldErrors({}); }}
            className="mb-6"
          >
            {Object.keys(fieldErrors).length > 0 && (
              <ul className="mt-2 list-disc list-inside text-lg">
                {Object.entries(fieldErrors).map(([field, error]) => (
                  <li key={field} className="mb-1">
                    <strong className="capitalize">{field.replace(/([A-Z])/g, " $1").trim()}:</strong> {error}
                  </li>
                ))}
              </ul>
            )}
          </Alert>
        )}

        {/* Review Header */}
        <div className="bg-gradient-to-r from-blue-50 to-blue-100 dark:from-blue-950 dark:to-blue-900 border border-current rounded-lg p-6 mb-6 opacity-90">
          <h2 className="text-2xl font-semibold flex items-center mb-3 opacity-90">
            <CheckCircleIcon className="w-8 h-8 mr-3" />
            Review and Submit
          </h2>
          <p className="text-lg opacity-70">
            Please carefully review the following speaker details. If everything looks correct, click the <strong>Submit</strong> button to create the new speaker.
          </p>
        </div>

        {/* Contact Information */}
        <FormCard
          title="Contact Information"
          icon={UserIcon}
          description="Basic contact details and preferences"
          maxWidth="full"
          className="mb-6"
          action={
            <button
              onClick={() => navigate("/admin/speakers/add/step-3")}
              className="inline-flex items-center text-base text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
            >
              <PencilSquareIcon className="w-5 h-5 mr-1" />
              {sectionHasErrors("contact") ? "Fix" : "Edit"}
            </button>
          }
        >
          <div className="space-y-4">
            {speakerData.type === REPRESENTATIVE_SPEAKER_TYPE_OF_ID && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <ReviewField
                  label="Representative Organization Name"
                  value={speakerData.representitiveOrganizationName}
                  error={fieldErrors.representitiveOrganizationName}
                />
                <ReviewField
                  label="Representative Organization Type"
                  value={getOrganizationTypeLabel(speakerData.representitiveOrganizationType)}
                  error={fieldErrors.representitiveOrganizationType}
                />
              </div>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <ReviewField label="First Name" value={speakerData.firstName} error={fieldErrors.firstName} />
              <ReviewField label="Last Name" value={speakerData.lastName} error={fieldErrors.lastName} />
              <ReviewField label="Email" value={speakerData.email} error={fieldErrors.email} />
              <ReviewField
                label="Phone"
                value={`${speakerData.phone} (${getPhoneTypeLabel(speakerData.phoneType)})`}
                error={fieldErrors.phone || fieldErrors.phoneType}
              />
              {speakerData.phoneType === SPEAKER_PHONE_TYPE_WORK && speakerData.phoneExtension && (
                <ReviewField label="Phone Extension" value={speakerData.phoneExtension} />
              )}
              <ReviewField label="OK to Email" value={speakerData.isOkToEmail ? "Yes" : "No"} />
              <ReviewField label="OK to Text" value={speakerData.isOkToText ? "Yes" : "No"} />
              {speakerData.otherPhone && (
                <ReviewField
                  label="Other Phone"
                  value={`${speakerData.otherPhone} (${getPhoneTypeLabel(speakerData.otherPhoneType)})`}
                />
              )}
            </div>
          </div>
        </FormCard>

        {/* Address Information */}
        <FormCard
          title={speakerData.hasShippingAddress ? "Billing Address" : "Address Information"}
          icon={speakerData.hasShippingAddress ? HomeIcon : MapPinIcon}
          description={speakerData.hasShippingAddress ? "Primary billing address" : "Primary address for the speaker"}
          maxWidth="full"
          className="mb-6"
          action={
            <button
              onClick={() => navigate("/admin/speakers/add/step-4")}
              className="inline-flex items-center text-base text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
            >
              <PencilSquareIcon className="w-5 h-5 mr-1" />
              {sectionHasErrors("address") ? "Fix" : "Edit"}
            </button>
          }
        >
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <ReviewField label="Address" value={speakerData.addressLine1} error={fieldErrors.addressLine1} />
            {speakerData.addressLine2 && <ReviewField label="Address Line 2" value={speakerData.addressLine2} />}
            <ReviewField label="City" value={speakerData.city} error={fieldErrors.city} />
            <ReviewField label="Province/Territory" value={speakerData.region} error={fieldErrors.region} />
            <ReviewField label="Postal Code" value={speakerData.postalCode} error={fieldErrors.postalCode} />
            <ReviewField label="Country" value={speakerData.country} error={fieldErrors.country} />
          </div>
        </FormCard>

        {/* Shipping Address */}
        {speakerData.hasShippingAddress && (
          <FormCard
            title="Shipping Address"
            icon={TruckIcon}
            description="Where materials and packages should be delivered"
            maxWidth="full"
            className="mb-6"
          >
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <ReviewField label="Contact Name" value={speakerData.shippingName} error={fieldErrors.shippingName} />
              <ReviewField label="Phone" value={speakerData.shippingPhone} error={fieldErrors.shippingPhone} />
              <ReviewField label="Address" value={speakerData.shippingAddressLine1} error={fieldErrors.shippingAddressLine1} />
              {speakerData.shippingAddressLine2 && <ReviewField label="Address Line 2" value={speakerData.shippingAddressLine2} />}
              <ReviewField label="City" value={speakerData.shippingCity} error={fieldErrors.shippingCity} />
              <ReviewField label="Province/Territory" value={speakerData.shippingRegion} error={fieldErrors.shippingRegion} />
              <ReviewField label="Postal Code" value={speakerData.shippingPostalCode} error={fieldErrors.shippingPostalCode} />
              <ReviewField label="Country" value={speakerData.shippingCountry} error={fieldErrors.shippingCountry} />
            </div>
          </FormCard>
        )}

        {/* Account Information */}
        <FormCard
          title="Account Information"
          icon={ClipboardDocumentIcon}
          description="Skills, insurance, and service details"
          maxWidth="full"
          className="mb-6"
          action={
            <button
              onClick={() => navigate("/admin/speakers/add/step-5")}
              className="inline-flex items-center text-base text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
            >
              <PencilSquareIcon className="w-5 h-5 mr-1" />
              {sectionHasErrors("account") ? "Fix" : "Edit"}
            </button>
          }
        >
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <ReviewField
                label="Level"
                value={speakerData.level === "level1" ? "Level 1 (unpaid)" : speakerData.level === "level2" ? "Level 2 (paid)" : "Not specified"}
                error={fieldErrors.level}
              />
            </div>

            {/* Availability Table */}
            {speakerData.availability && (
              <div>
                <p className="text-lg font-medium opacity-70 mb-3">Weekly Availability</p>
                <div className="overflow-x-auto border border-current rounded-lg">
                  <table className="min-w-full divide-y divide-current">
                    <thead className={getThemeClasses('table-header')}>
                      <tr>
                        <th className="px-6 py-4 text-left text-base font-medium opacity-70 uppercase">Day</th>
                        <th className="px-6 py-4 text-center text-base font-medium opacity-70 uppercase">AM</th>
                        <th className="px-6 py-4 text-center text-base font-medium opacity-70 uppercase">PM</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-current">
                      {["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"].map((day, index) => (
                        <tr key={day}>
                          <td className="px-6 py-4 text-lg font-medium capitalize opacity-90">{["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"][index]}</td>
                          <td className="px-6 py-4 text-center">
                            {speakerData.availability[day]?.am ? (
                              <CheckIcon className="inline w-6 h-6 text-green-600" />
                            ) : (
                              <XMarkIcon className="inline w-6 h-6 opacity-30" />
                            )}
                          </td>
                          <td className="px-6 py-4 text-center">
                            {speakerData.availability[day]?.pm ? (
                              <CheckIcon className="inline w-6 h-6 text-green-600" />
                            ) : (
                              <XMarkIcon className="inline w-6 h-6 opacity-30" />
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {speakerData.skillSets && (
              <div>
                <SkillSetsDisplay values={parseArrayValue(speakerData.skillSets)} label="Skill Sets" variant="primary" />
                {fieldErrors.skillSets && <p className="mt-2 text-lg text-red-600 bg-red-50 p-3 rounded">{fieldErrors.skillSets}</p>}
              </div>
            )}

            {speakerData.insuranceRequirements && (
              <div>
                <InsuranceRequirementsDisplay values={parseArrayValue(speakerData.insuranceRequirements)} label="Insurance Requirements" variant="info" />
                {fieldErrors.insuranceRequirements && <p className="mt-2 text-lg text-red-600 bg-red-50 p-3 rounded">{fieldErrors.insuranceRequirements}</p>}
              </div>
            )}

            {speakerData.vehicleTypes && speakerData.vehicleTypes.length > 0 && (
              <div>
                <VehicleTypesDisplay values={parseArrayValue(speakerData.vehicleTypes)} label="Vehicle Types" variant="warning" />
                {fieldErrors.vehicleTypes && <p className="mt-2 text-lg text-red-600 bg-red-50 p-3 rounded">{fieldErrors.vehicleTypes}</p>}
              </div>
            )}

            {speakerData.serviceFeeId && (
              <div>
                <ServiceFeeDisplay value={speakerData.serviceFeeId} label="Service Fee" showAmount={true} />
                {fieldErrors.serviceFeeId && <p className="mt-2 text-lg text-red-600 bg-red-50 p-3 rounded">{fieldErrors.serviceFeeId}</p>}
              </div>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {speakerData.hourlySalaryDesired && (
                <ReviewField label="Hourly Rate" value={`$${speakerData.hourlySalaryDesired}/hr`} error={fieldErrors.hourlySalaryDesired} />
              )}
              <ReviewField label="Member Dues Date" value={speakerData.duesDate} error={fieldErrors.duesDate} />
              <ReviewField label="Police Check Expiry" value={speakerData.policeCheck} error={fieldErrors.policeCheck} />
              <ReviewField label="Preferred Language" value={speakerData.preferredLanguage} error={fieldErrors.preferredLanguage} />
            </div>

            {speakerData.emergencyContactName && (
              <div className="pt-4 border-t border-current">
                <p className="text-base font-medium opacity-70 mb-4">Emergency Contact</p>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <ReviewField label="Name" value={speakerData.emergencyContactName} />
                  <ReviewField label="Relationship" value={speakerData.emergencyContactRelationship} />
                  <ReviewField label="Phone" value={speakerData.emergencyContactTelephone} />
                  {speakerData.emergencyContactAlternativeTelephone && (
                    <ReviewField label="Alternative Phone" value={speakerData.emergencyContactAlternativeTelephone} />
                  )}
                </div>
              </div>
            )}
          </div>
        </FormCard>

        {/* Metrics Information */}
        <FormCard
          title="Metrics Information"
          icon={ChartBarSquareIcon}
          description="Demographics and performance metrics"
          maxWidth="full"
          className="mb-6"
          action={
            <button
              onClick={() => navigate("/admin/speakers/add/step-6")}
              className="inline-flex items-center text-base text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
            >
              <PencilSquareIcon className="w-5 h-5 mr-1" />
              {sectionHasErrors("metrics") ? "Fix" : "Edit"}
            </button>
          }
        >
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <ReviewField
                label="Is Job Seeker"
                value={speakerData.isJobSeeker === SPEAKER_IS_JOB_SEEKER_YES ? "Yes" : "No"}
                error={fieldErrors.isJobSeeker}
              />
              <ReviewField label="Gender" value={getGenderLabel(speakerData.gender)} error={fieldErrors.gender} />
              {speakerData.gender === SPEAKER_GENDER_OTHER && (
                <ReviewField label="Gender (Other)" value={speakerData.genderOther} />
              )}
              <ReviewField label="Birth Date (Optional)" value={speakerData.birthDate} error={fieldErrors.birthDate} />
              <ReviewField label="Join Date" value={speakerData.joinDate} error={fieldErrors.joinDate} />
            </div>

            {speakerData.howDidYouHearAboutUsID && (
              <div>
                <HowHearAboutUsDisplay value={speakerData.howDidYouHearAboutUsID} label="How did you hear about us?" />
                {fieldErrors.howDidYouHearAboutUsID && <p className="mt-1 text-base text-red-600 bg-red-50 p-2 rounded">{fieldErrors.howDidYouHearAboutUsID}</p>}
              </div>
            )}

            {speakerData.tags && speakerData.tags.length > 0 && (
              <div>
                <TagsDisplay values={parseArrayValue(speakerData.tags)} label="Tags" variant="success" />
                {fieldErrors.tags && <p className="mt-1 text-base text-red-600 bg-red-50 p-2 rounded">{fieldErrors.tags}</p>}
              </div>
            )}

            {speakerData.additionalComment && (
              <ReviewField label="Additional Comments" value={speakerData.additionalComment} />
            )}
          </div>
        </FormCard>

        {/* Form Actions */}
        <div className="flex flex-col sm:flex-row gap-3 mt-6">
          <Button
            type="button"
            variant="outline"
            onClick={handleBack}
            icon={ArrowLeftIcon}
            className="flex-1"
          >
            Back
          </Button>
          <Button
            type="button"
            variant="success"
            onClick={onSubmitClick}
            icon={CheckCircleIcon}
            disabled={isLoading}
            loading={isLoading}
            className="flex-1"
          >
            {isLoading ? "Submitting..." : "Submit Speaker"}
          </Button>
        </div>
      </StepWizard>
    </UIXThemeProvider>
  );
}

export default AdminSpeakerAddStep7Page;
