// File Path: monorepo/web/frontend/src/pages/Admin/TaskItem/AssignFacilitatorOrSpeaker/Step3SpeakerPage.jsx

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import {
  UIXThemeProvider,
  StaffWizardFormStep,
  FormSection,
  Input,
  Alert,
  Card,
  Badge,
  Button,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  UserGroupIcon,
  UserIcon,
  ExclamationTriangleIcon,
  PhoneIcon,
  EnvelopeIcon,
  CheckCircleIcon,
} from "@heroicons/react/24/outline";
import { useTaskManager } from "../../../../services/Services";

function AdminTaskItemAssignFacilitatorOrSpeakerStep3SpeakerPage() {
  const navigate = useNavigate();
  const { id } = useParams();
  const taskManager = useTaskManager();
  const { getThemeClasses } = useUIXTheme();

  const [selectedRole, setSelectedRole] = useState("speaker");
  const [selectedPersonId, setSelectedPersonId] = useState("");
  const [estimatedHours, setEstimatedHours] = useState("");
  const [errors, setErrors] = useState({});
  const [speakers, setSpeakers] = useState([]);
  const [isLoadingSpeakers, setIsLoadingSpeakers] = useState(false);
  const [taskItem, setTaskItem] = useState(null);

  const wizardSteps = [
    { title: "Event Details" },
    { title: "Select Person" },
    { title: "Acceptance Status" },
    { title: "Review & Submit" },
  ];

  const onUnauthorized = () => {
    navigate("/login?unauthorized=true");
  };

  const fetchTaskItemForEstimatedHours = useCallback(async () => {
    try {
      const task = await taskManager.getTaskDetail(id, onUnauthorized);
      setTaskItem(task);

      // Pre-fill estimated hours from event contract if available
      if (task?.eventContractEstimatedContractHours && task.eventContractEstimatedContractHours > 0) {
        setEstimatedHours(task.eventContractEstimatedContractHours.toString());
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error fetching task item for estimated hours:", error);
      }
      // Don't show error to user, just leave estimatedHours empty
    }
  }, [id, taskManager, navigate]);

  const fetchAssignableSpeakers = useCallback(async () => {
    setIsLoadingSpeakers(true);
    try {
      // Force refresh = true to always fetch fresh data from backend, bypassing cache
      const response = await taskManager.getAssignableSpeakers(id, onUnauthorized, true);
      if (import.meta.env.DEV) {
        console.log("Assignable speakers response:", response);
      }
      if (import.meta.env.DEV) {
        console.log("Speaker IDs:", response.results?.map(s => ({ name: s.name, id: s.id })));
      }

      const allSpeakers = response.results || [];

      // Filter speakers to only include those with hourly_salary_desired set
      const speakersWithRate = allSpeakers.filter(
        (s) => s.hourlySalaryDesired && s.hourlySalaryDesired > 0
      );

      // Track how many were filtered out
      const filteredOutCount = allSpeakers.length - speakersWithRate.length;

      if (import.meta.env.DEV) {
        console.log(`Filtered out ${filteredOutCount} speakers without hourly rate`);
      }
      if (import.meta.env.DEV) {
        console.log(`Showing ${speakersWithRate.length} speakers with hourly rate`);
      }

      setSpeakers(speakersWithRate);

      // Store the filtered count for display
      if (filteredOutCount > 0) {
        setErrors(prevErrors => ({
          ...prevErrors,
          filteredInfo: `${filteredOutCount} speaker(s) hidden because they don't have an hourly rate set in their profile.`
        }));
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error fetching assignable speakers:", error);
      }
      setErrors({ speakers: "Failed to load available speakers" });
    } finally {
      setIsLoadingSpeakers(false);
    }
  }, [id, taskManager, navigate]);

  // Load saved data from sessionStorage and fetch speakers
  useEffect(() => {
    const savedRole = sessionStorage.getItem(`assign_facilitator_speaker_${id}_role`);
    const savedPersonId = sessionStorage.getItem(`assign_facilitator_speaker_${id}_person_id`);
    const savedHours = sessionStorage.getItem(`assign_facilitator_speaker_${id}_hours`);

    if (!savedRole || savedRole !== "speaker") {
      // If no role selected or wrong role, redirect back to step 1
      navigate(`/admin/task/${id}/assign-facilitator-speaker/step-1`);
      return;
    }

    setSelectedRole(savedRole);
    if (savedPersonId) setSelectedPersonId(savedPersonId);

    // If savedHours exists, use it; otherwise fetch from task item
    if (savedHours) {
      setEstimatedHours(savedHours);
    } else {
      // Fetch task item to get initial estimated hours from event_contract_estimated_contract_hours
      fetchTaskItemForEstimatedHours();
    }

    // Fetch assignable speakers
    fetchAssignableSpeakers();
  }, [id, navigate, fetchTaskItemForEstimatedHours, fetchAssignableSpeakers]);

  const handleNext = () => {
    if (import.meta.env.DEV) {
      console.log("handleNext called - Current state:", {
        selectedPersonId,
        estimatedHours,
      });
    }

    const newErrors = {};

    if (!selectedPersonId) {
      newErrors.person = `Please select a speaker before continuing`;
    }

    if (!estimatedHours || estimatedHours === "0") {
      newErrors.hours = "Please enter estimated hours";
    } else {
      const hours = parseFloat(estimatedHours);
      if (isNaN(hours) || hours <= 0) {
        newErrors.hours = "Please enter a valid number greater than 0";
      }
    }

    if (Object.keys(newErrors).length > 0) {
      if (import.meta.env.DEV) {
        console.log("Validation errors:", newErrors);
      }
      setErrors(newErrors);
      return;
    }

    // Find the selected speaker's name
    const selectedSpeaker = speakers.find(s => s.id === selectedPersonId);
    const speakerName = selectedSpeaker ? selectedSpeaker.name : "Unknown";

    // Save selections to sessionStorage
    sessionStorage.setItem(`assign_facilitator_speaker_${id}_person_id`, selectedPersonId);
    sessionStorage.setItem(`assign_facilitator_speaker_${id}_person_name`, speakerName);
    sessionStorage.setItem(`assign_facilitator_speaker_${id}_hours`, estimatedHours);
    if (import.meta.env.DEV) {
      console.log("Data saved to sessionStorage, navigating to step 4");
    }
    setErrors({});

    navigate(`/admin/task/${id}/assign-facilitator-speaker/step-4`);
  };

  const handleBack = () => {
    navigate(`/admin/task/${id}/assign-facilitator-speaker/step-1`);
  };

  const handleCancel = () => {
    // Clear all sessionStorage on cancel
    sessionStorage.removeItem(`assign_facilitator_speaker_${id}_role`);
    sessionStorage.removeItem(`assign_facilitator_speaker_${id}_person_id`);
    sessionStorage.removeItem(`assign_facilitator_speaker_${id}_hours`);
    navigate("/admin/tasks");
  };

  return (
    <UIXThemeProvider>
      <StaffWizardFormStep
        wizardSteps={wizardSteps}
        currentStep={2}
        wizardTitle="Assign Facilitator or Speaker"
        wizardIcon={UserGroupIcon}
        stepTitle="Select Speaker"
        stepSubtitle="Select a speaker and provide estimated hours"
        stepIcon={UserIcon}
        errors={errors}
        showFormCard={true}
        actionLayout="between"
        contentMaxWidth="4xl"
        showActions={true}
        actions={[
          {
            label: "Next: Acceptance Status",
            variant: "primary",
            onClick: handleNext,
          },
        ]}
        onBack={handleBack}
        onCancel={handleCancel}
        backLabel="Back"
        cancelLabel="Cancel"
      >
        <FormSection
          title="Select Speaker"
          description="Select a speaker based on skill sets and availability"
          className="mb-6"
        >
          {/* Info about filtered speakers */}
          {errors.filteredInfo && (
            <Alert variant="info" icon={ExclamationTriangleIcon} className="mb-4">
              <p className="font-semibold mb-1">Some Speakers Not Shown</p>
              <p>{errors.filteredInfo}</p>
            </Alert>
          )}

          {/* Count display */}
          {!isLoadingSpeakers && speakers.length > 0 && (
            <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
              <p className="text-sm font-medium text-blue-800">
                {speakers.length} speaker{speakers.length !== 1 ? 's' : ''} available with hourly rates set
              </p>
            </div>
          )}

          {/* DEBUG: Current Selection Indicator - Only shown in development */}
          {import.meta.env.DEV && selectedPersonId && (
            <div className="mb-4 p-3 bg-green-100 border-2 border-green-500 rounded-lg">
              <p className="font-semibold text-green-800">
                ✓ Selected Speaker ID: {selectedPersonId}
              </p>
              <p className="text-sm text-green-700">
                Speaker: {speakers.find(s => s.id === selectedPersonId)?.name || "Unknown"}
              </p>
            </div>
          )}
          {import.meta.env.DEV && !selectedPersonId && (
            <div className="mb-4 p-3 bg-yellow-100 border-2 border-yellow-500 rounded-lg">
              <p className="font-semibold text-yellow-800">
                ⚠ No speaker selected yet - Click on a speaker card below to select
              </p>
            </div>
          )}

          {isLoadingSpeakers ? (
            <div className="flex items-center justify-center py-12">
              <div className="text-center">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto"></div>
                <p className={`mt-4 text-sm ${getThemeClasses("text-secondary")}`}>Loading available speakers...</p>
              </div>
            </div>
          ) : errors.speakers ? (
            <Alert variant="error" icon={ExclamationTriangleIcon}>
              <p className="font-semibold mb-2">Error Loading Speakers</p>
              <p>{errors.speakers}</p>
            </Alert>
          ) : speakers.length === 0 ? (
            <Alert variant="warning" icon={ExclamationTriangleIcon}>
              <p className="font-semibold mb-2">No Available Speakers</p>
              <p>
                No speakers with hourly rates set match the required skill sets for this event.
                Please ensure speakers have their hourly rate configured in their profile settings.
              </p>
            </Alert>
          ) : (
            <div className="space-y-4">
              {errors.person && (
                <Alert variant="error" icon={ExclamationTriangleIcon}>
                  {errors.person}
                </Alert>
              )}

              <div className="grid grid-cols-1 gap-4">
                {speakers.map((speaker) => (
                  <div
                    key={speaker.id}
                    className={`p-4 cursor-pointer transition-all rounded-lg border-2 ${
                      selectedPersonId === speaker.id
                        ? "ring-2 ring-primary-600 bg-primary-50 border-primary-600"
                        : `hover:${getThemeClasses("bg-disabled")} ${getThemeClasses("border-secondary")}`
                    }`}
                    onClick={() => {
                      if (import.meta.env.DEV) {
                        console.log("Speaker clicked:", { name: speaker.name, id: speaker.id });
                      }
                      setSelectedPersonId(speaker.id);
                      if (import.meta.env.DEV) {
                        console.log("Selected person ID set to:", speaker.id);
                      }
                    }}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}>
                            {speaker.name}
                          </h3>
                          {selectedPersonId === speaker.id && (
                            <CheckCircleIcon className="h-6 w-6 text-primary-600" />
                          )}
                          {speaker.isAway && (
                            <Badge variant="warning">Away</Badge>
                          )}
                        </div>

                        <div className="mt-2 space-y-1">
                          {speaker.email && (
                            <div className={`flex items-center text-sm ${getThemeClasses("text-secondary")}`}>
                              <EnvelopeIcon className="h-4 w-4 mr-2" />
                              {speaker.email}
                            </div>
                          )}
                          {speaker.phone && (
                            <div className={`flex items-center text-sm ${getThemeClasses("text-secondary")}`}>
                              <PhoneIcon className="h-4 w-4 mr-2" />
                              {speaker.phone}
                              {speaker.phoneExtension && ` ext. ${speaker.phoneExtension}`}
                            </div>
                          )}
                          {speaker.representitiveOrganizationName && (
                            <div className={`text-sm ${getThemeClasses("text-secondary")}`}>
                              Organization: {speaker.representitiveOrganizationName}
                            </div>
                          )}
                        </div>

                        {speaker.skillSets && speaker.skillSets.length > 0 && (
                          <div className="mt-3">
                            <p className={`text-xs font-medium ${getThemeClasses("text-primary")} mb-1`}>Skill Sets:</p>
                            <div className="flex flex-wrap gap-1">
                              {speaker.skillSets.map((skill) => (
                                <Badge key={skill.id} variant="info" size="sm">
                                  {skill.name}
                                </Badge>
                              ))}
                            </div>
                          </div>
                        )}
                      </div>

                      <div className="ml-4 text-right space-y-2">
                        {/* Hourly Rate - Prominent Display */}
                        <div className="bg-green-50 border border-green-200 rounded-lg p-2">
                          <div className="text-xs font-medium text-green-700 uppercase">
                            Hourly Rate
                          </div>
                          <div className="text-xl font-bold text-green-800">
                            ${speaker.hourlySalaryDesired?.toLocaleString() || 0}
                          </div>
                          <div className="text-xs text-green-600">per hour</div>
                        </div>

                        {/* Activity Count */}
                        <div className={`border-t ${getThemeClasses("border-secondary")} pt-2`}>
                          <div className={`text-xs ${getThemeClasses("text-muted")}`}>
                            Activity (30 Days)
                          </div>
                          <div className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}>
                            {speaker.contactsLast30Days || 0}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </FormSection>

        <FormSection
          title="Estimated Hours"
          description="Enter the estimated hours for this assignment"
          className="mb-6"
        >
          <div className="space-y-2">
            <label className={`block text-sm font-medium ${getThemeClasses("text-primary")}`}>
              Estimated Hours <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              inputMode="decimal"
              value={estimatedHours}
              onChange={(e) => {
                const value = e.target.value;
                if (import.meta.env.DEV) {
                  console.log("Estimated hours input changed:", value);
                }
                // Allow only positive numbers with decimals
                if (value === "" || /^\d*\.?\d*$/.test(value)) {
                  setEstimatedHours(value);
                  if (import.meta.env.DEV) {
                    console.log("Estimated hours updated to:", value);
                  }
                }
              }}
              placeholder="Enter estimated hours (e.g., 6.5)"
              className={`w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 ${
                errors.hours ? "border-red-500" : getThemeClasses("border-secondary")
              }`}
            />
            {errors.hours && (
              <p className="text-sm text-red-600">{errors.hours}</p>
            )}
            <p className={`text-sm ${getThemeClasses("text-muted")}`}>
              Enter the estimated number of hours for this assignment (decimals are allowed, e.g., 6.5)
            </p>
          </div>
        </FormSection>

        <Alert variant="info" icon={ExclamationTriangleIcon}>
          <p className="font-semibold mb-2">Note:</p>
          <p>
            The speaker selection is based on skill sets that match
            the event requirements. Make sure to verify availability before proceeding.
          </p>
        </Alert>
      </StaffWizardFormStep>
    </UIXThemeProvider>
  );
}

export default AdminTaskItemAssignFacilitatorOrSpeakerStep3SpeakerPage;