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

import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router";
import { useAuthManager } from "../../../../services/Services";
import {
  WizardSearchStep,
  UIXThemeProvider,
} from "../../../../components/UIX";
import {
  UserPlusIcon,
  MagnifyingGlassIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";

function AdminSpeakerAddStep1PartAPage() {
  const authManager = useAuthManager();
  const navigate = useNavigate();

  // Component states
  const [errors, setErrors] = useState({});
  const [isLoading] = useState(false);
  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
  });

  // Check authentication
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }
    window.scrollTo(0, 0);
  }, [authManager, navigate]);

  // Configuration for wizard steps
  const wizardSteps = [
    { title: "Search" },
    { title: "Type" },
    { title: "Contact" },
    { title: "Address" },
    { title: "Account" },
    { title: "Metrics" },
    { title: "Comments" },
  ];

  // Field configuration for search form - speaker search criteria
  const searchFields = [
    {
      name: "firstName",
      label: "First Name",
      type: "text",
      placeholder: "Enter first name",
      section: "details",
      icon: UserIcon,
    },
    {
      name: "lastName",
      label: "Last Name",
      type: "text",
      placeholder: "Enter last name",
      section: "details",
      icon: UserIcon,
    },
    {
      name: "email",
      label: "Email Address",
      type: "email",
      placeholder: "Enter email address",
      section: "contact",
      icon: EnvelopeIcon,
    },
    {
      name: "phone",
      label: "Phone Number",
      type: "tel",
      placeholder: "Enter phone number",
      section: "contact",
      icon: PhoneIcon,
    },
  ];

  // Validate search criteria
  const validateSearchCriteria = (data) => {
    const errors = {};

    // Check if at least one search criteria is provided
    if (
      !data.firstName?.trim() &&
      !data.lastName?.trim() &&
      !data.email?.trim() &&
      !data.phone?.trim()
    ) {
      errors.message = "Please enter at least one search criteria";
    }

    return errors;
  };

  // Event handlers
  const handleSearch = (data) => {
    if (import.meta.env.DEV) {
      console.log("handleSearch: Beginning...", data);
    }

    // Validate
    const errors = validateSearchCriteria(data);
    if (Object.keys(errors).length > 0) {
      setErrors(errors);
      return;
    }

    // Clear any previous errors
    setErrors({});

    // Build search params using form data
    const searchParams = new URLSearchParams();
    if (data.firstName?.trim()) {
      searchParams.append("fn", data.firstName.trim());
    }
    if (data.lastName?.trim()) {
      searchParams.append("ln", data.lastName.trim());
    }
    if (data.email?.trim()) {
      searchParams.append("e", data.email.trim());
    }
    if (data.phone?.trim()) {
      searchParams.append("p", data.phone.trim());
    }

    // Navigate to results page with search parameters
    navigate(`/admin/speakers/add/step-1-results?${searchParams.toString()}`);
  };

  const handleSkipSearch = () => {
    if (import.meta.env.DEV) {
      console.log("Skipping speaker search - navigating to speaker creation");
    }

    // Clear any existing speaker creation state
    sessionStorage.removeItem("FLASHPOINTTRAINING_SPEAKER_CREATION_STATE");

    // Navigate directly to step 2
    navigate("/admin/speakers/add/step-2");
  };

  const handleCancel = () => {
    navigate("/admin/speakers");
  };

  return (
    <UIXThemeProvider>
      <WizardSearchStep
        wizardSteps={wizardSteps}
        currentStep={1}
        wizardTitle="Add New Speaker"
        wizardIcon={WrenchScrewdriverIcon}
        formData={formData}
        onFormDataChange={setFormData}
        searchFields={searchFields}
        errors={errors}
        onSearch={handleSearch}
        onCancel={handleCancel}
        onSkipSearch={handleSkipSearch}
        entityName="speaker"
        isLoading={isLoading}
        skipIcon={UserPlusIcon}
        searchTitle="Search for Existing Speaker"
        searchSubtitle="Check for existing speakers before creating a new one"
        searchButtonLabel="Search Speakers"
        skipButtonLabel="Add New Speaker"
        skipDescription="If you're sure this is a new speaker, skip the search and proceed directly to creation"
      />
    </UIXThemeProvider>
  );
}

export default AdminSpeakerAddStep1PartAPage;
