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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import {
  useAuthManager,
  useFacilitatorManager,
} from "../../../../services/Services";
import {
  WrenchScrewdriverIcon,
  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,
  CertificationDisplay,
  SpecializationDisplay,
} from "../../../../components/business/displays";
import {
  FACILITATOR_GENDER_OTHER,
} from "../../../../constants/Facilitator";

const REPRESENTATIVE_FACILITATOR_TYPE_OF_ID = 2;
const FACILITATOR_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 AdminFacilitatorAddStep7Page() {
  const authManager = useAuthManager();
  const facilitatorManager = useFacilitatorManager();
  const navigate = useNavigate();

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

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

  const loadFacilitatorState = useCallback(() => {
    try {
      const existing = sessionStorage.getItem("FLASHPOINTTRAINING_FACILITATOR_CREATION_STATE");
      if (existing) {
        const facilitatorState = JSON.parse(existing);
        setFacilitatorData(facilitatorState);
      } else {
        navigate("/admin/facilitators/add/step-1-search");
      }
    } catch (error) {
      console.error("Error loading facilitator state:", error);
      navigate("/admin/facilitators/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", "certifications", "specializations", "vehicleTypes", "serviceFeeId", "hourlySalaryDesired", "policeCheck", "preferredLanguage"];
    const metricsFields = ["tags", "howDidYouHearAboutUsID", "gender", "joinDate"];

    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", "certifications", "specializations", "vehicleTypes", "serviceFeeId", "hourlySalaryDesired", "policeCheck", "preferredLanguage"],
      metrics: ["tags", "howDidYouHearAboutUsID", "gender", "joinDate"],
    };
    return fieldsInSection[section]?.some((field) => fieldErrors[field]);
  }, [fieldErrors]);

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

    try {
      if (!facilitatorData) {
        throw new Error("No facilitator data found");
      }

      const processedData = processFacilitatorData(facilitatorData);
      console.log("Submitting facilitator data:", processedData);
      const response = await facilitatorManager.createFacilitator(processedData, () => navigate("/login?unauthorized=true"));

      sessionStorage.removeItem("FLASHPOINTTRAINING_FACILITATOR_CREATION_STATE");
      navigate(`/admin/facilitator/${response.id}`, {
        state: { successMessage: "Facilitator created successfully!" },
      });
    } catch (error) {
      console.error("Failed to create facilitator:", 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", "certifications", "specializations", "vehicleTypes", "serviceFeeId", "hourlySalaryDesired", "policeCheck", "preferredLanguage", "tags", "howDidYouHearAboutUsID", "gender", "joinDate", "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 facilitator. 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);
    }
  }, [facilitatorData, facilitatorManager, navigate, getSectionWithError]);

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

    // Date conversions
    const dateFields = ["policeCheck", "joinDate", "autoInsuranceExpiryDate", "wsibInsuranceDate"];
    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", "certifications", "specializations"];
    arrayFields.forEach((field) => {
      if (typeof processed[field] === "string") {
        processed[field] = processed[field].split(",").map((id) => id.trim()).filter(Boolean);
      }
    });

    // Identity array
    if (typeof processed.identifyAs === "string") {
      processed.identifyAs = processed.identifyAs.split(",").map((id) => parseInt(id.trim())).filter(Boolean);
    } else if (Array.isArray(processed.identifyAs)) {
      processed.identifyAs = processed.identifyAs.map((id) => (typeof id === "string" ? parseInt(id) : id));
    }

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

    const intFields = ["gender", "type", "representitiveOrganizationType", "phoneType", "otherPhoneType", "level"];
    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 getLevelLabel = (level) => {
    switch (level) {
      case 1: return "Level 1 (in training)";
      case 2: return "Level 2 (secondary facilitator)";
      case 3: return "Level 3 (lead facilitator)";
      case 4: return "Level 4 (trainer)";
      default: return "Not specified";
    }
  };

  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/facilitators/add/step-6");
  }, [navigate]);

  if (!facilitatorData) {
    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 Facilitator"
        subtitle="Review and submit the new facilitator information"
        icon={WrenchScrewdriverIcon}
      >
        {/* 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 facilitator details. If everything looks correct, click the <strong>Submit</strong> button to create the new facilitator.
          </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/facilitators/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">
            {facilitatorData.type === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <ReviewField
                  label="Representative Organization Name"
                  value={facilitatorData.representitiveOrganizationName}
                  error={fieldErrors.representitiveOrganizationName}
                />
                <ReviewField
                  label="Representative Organization Type"
                  value={getOrganizationTypeLabel(facilitatorData.representitiveOrganizationType)}
                  error={fieldErrors.representitiveOrganizationType}
                />
              </div>
            )}

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

        {/* Address Information */}
        <FormCard
          title={facilitatorData.hasShippingAddress ? "Billing Address" : "Address Information"}
          icon={facilitatorData.hasShippingAddress ? HomeIcon : MapPinIcon}
          description={facilitatorData.hasShippingAddress ? "Primary billing address" : "Primary address for the facilitator"}
          maxWidth="full"
          className="mb-6"
          action={
            <button
              onClick={() => navigate("/admin/facilitators/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={facilitatorData.addressLine1} error={fieldErrors.addressLine1} />
            {facilitatorData.addressLine2 && <ReviewField label="Address Line 2" value={facilitatorData.addressLine2} />}
            <ReviewField label="City" value={facilitatorData.city} error={fieldErrors.city} />
            <ReviewField label="Province/Territory" value={facilitatorData.region} error={fieldErrors.region} />
            <ReviewField label="Postal Code" value={facilitatorData.postalCode} error={fieldErrors.postalCode} />
            <ReviewField label="Country" value={facilitatorData.country} error={fieldErrors.country} />
          </div>
        </FormCard>

        {/* Shipping Address */}
        {facilitatorData.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={facilitatorData.shippingName} error={fieldErrors.shippingName} />
              <ReviewField label="Phone" value={facilitatorData.shippingPhone} error={fieldErrors.shippingPhone} />
              <ReviewField label="Address" value={facilitatorData.shippingAddressLine1} error={fieldErrors.shippingAddressLine1} />
              {facilitatorData.shippingAddressLine2 && <ReviewField label="Address Line 2" value={facilitatorData.shippingAddressLine2} />}
              <ReviewField label="City" value={facilitatorData.shippingCity} error={fieldErrors.shippingCity} />
              <ReviewField label="Province/Territory" value={facilitatorData.shippingRegion} error={fieldErrors.shippingRegion} />
              <ReviewField label="Postal Code" value={facilitatorData.shippingPostalCode} error={fieldErrors.shippingPostalCode} />
              <ReviewField label="Country" value={facilitatorData.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/facilitators/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={getLevelLabel(parseInt(facilitatorData.level))}
                error={fieldErrors.level}
              />
            </div>

            {/* Availability Table */}
            {facilitatorData.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="bg-gray-50 dark:bg-gray-800 opacity-90">
                      <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">
                            {facilitatorData.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">
                            {facilitatorData.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>
            )}

            {facilitatorData.skillSets && (
              <div>
                <SkillSetsDisplay values={parseArrayValue(facilitatorData.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>
            )}

            {facilitatorData.certifications && facilitatorData.certifications.length > 0 && (
              <div>
                <CertificationDisplay values={parseArrayValue(facilitatorData.certifications)} label="Certifications" variant="success" />
                {fieldErrors.certifications && <p className="mt-2 text-lg text-red-600 bg-red-50 p-3 rounded">{fieldErrors.certifications}</p>}
              </div>
            )}

            {facilitatorData.specializations && facilitatorData.specializations.length > 0 && (
              <div>
                <SpecializationDisplay values={parseArrayValue(facilitatorData.specializations)} label="Specializations" variant="info" />
                {fieldErrors.specializations && <p className="mt-2 text-lg text-red-600 bg-red-50 p-3 rounded">{fieldErrors.specializations}</p>}
              </div>
            )}

            {facilitatorData.insuranceRequirements && (
              <div>
                <InsuranceRequirementsDisplay values={parseArrayValue(facilitatorData.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>
            )}

            {facilitatorData.vehicleTypes && facilitatorData.vehicleTypes.length > 0 && (
              <div>
                <VehicleTypesDisplay values={parseArrayValue(facilitatorData.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>
            )}

            {facilitatorData.serviceFeeId && (
              <div>
                <ServiceFeeDisplay value={facilitatorData.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">
              {facilitatorData.hourlySalaryDesired && (
                <ReviewField label="Hourly Rate" value={`$${facilitatorData.hourlySalaryDesired}/hr`} error={fieldErrors.hourlySalaryDesired} />
              )}
              <ReviewField label="Police Check Expiry" value={facilitatorData.policeCheck} error={fieldErrors.policeCheck} />
              <ReviewField label="Preferred Language" value={facilitatorData.preferredLanguage} error={fieldErrors.preferredLanguage} />
            </div>

            {facilitatorData.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={facilitatorData.emergencyContactName} />
                  <ReviewField label="Relationship" value={facilitatorData.emergencyContactRelationship} />
                  <ReviewField label="Phone" value={facilitatorData.emergencyContactTelephone} />
                  {facilitatorData.emergencyContactAlternativeTelephone && (
                    <ReviewField label="Alternative Phone" value={facilitatorData.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/facilitators/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="Gender" value={getGenderLabel(facilitatorData.gender)} error={fieldErrors.gender} />
              {facilitatorData.gender === FACILITATOR_GENDER_OTHER && (
                <ReviewField label="Gender (Other)" value={facilitatorData.genderOther} />
              )}
              <ReviewField label="Join Date" value={facilitatorData.joinDate} error={fieldErrors.joinDate} />
            </div>

            {facilitatorData.howDidYouHearAboutUsID && (
              <div>
                <HowHearAboutUsDisplay value={facilitatorData.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>
            )}

            {facilitatorData.tags && facilitatorData.tags.length > 0 && (
              <div>
                <TagsDisplay values={parseArrayValue(facilitatorData.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>
            )}

            {facilitatorData.additionalComment && (
              <ReviewField label="Additional Comments" value={facilitatorData.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 Facilitator"}
          </Button>
        </div>
      </StepWizard>
    </UIXThemeProvider>
  );
}

export default AdminFacilitatorAddStep7Page;
