// File Path: monorepo/web/frontend/src/pages/Admin/TaskItem/AssignFacilitatorOrSpeaker/Step3FacilitatorPage.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 AdminTaskItemAssignFacilitatorOrSpeakerStep3FacilitatorPage() {
  const navigate = useNavigate();
  const { id } = useParams();
  const taskManager = useTaskManager();
  const { getThemeClasses } = useUIXTheme();

  const [selectedRole, setSelectedRole] = useState("facilitator");
  const [selectedPersonId, setSelectedPersonId] = useState("");
  const [estimatedHours, setEstimatedHours] = useState("");
  const [errors, setErrors] = useState({});
  const [facilitators, setFacilitators] = useState([]);
  const [isLoadingFacilitators, setIsLoadingFacilitators] = 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 fetchAssignableFacilitators = useCallback(async () => {
    setIsLoadingFacilitators(true);
    try {
      // Force refresh = true to always fetch fresh data from backend, bypassing cache
      const response = await taskManager.getAssignableFacilitators(id, onUnauthorized, true);
      if (import.meta.env.DEV) {
        console.log("Assignable facilitators response:", response);
      }

      const allFacilitators = response.results || [];

      // Filter facilitators to only include those with hourly_salary_desired set
      const facilitatorsWithRate = allFacilitators.filter(
        (f) => f.hourlySalaryDesired && f.hourlySalaryDesired > 0
      );

      // Track how many were filtered out
      const filteredOutCount = allFacilitators.length - facilitatorsWithRate.length;

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

      setFacilitators(facilitatorsWithRate);

      // Store the filtered count for display
      if (filteredOutCount > 0) {
        setErrors(prevErrors => ({
          ...prevErrors,
          filteredInfo: `${filteredOutCount} facilitator(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 facilitators:", error);
      }
      setErrors({ facilitators: "Failed to load available facilitators" });
    } finally {
      setIsLoadingFacilitators(false);
    }
  }, [id, taskManager, navigate]);

  // Load saved data from sessionStorage and fetch facilitators
  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 !== "facilitator") {
      // 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 facilitators
    fetchAssignableFacilitators();
  }, [id, navigate, fetchTaskItemForEstimatedHours, fetchAssignableFacilitators]);

  const handleNext = () => {
    const newErrors = {};

    if (!selectedPersonId) {
      newErrors.person = `Please select a facilitator 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) {
      setErrors(newErrors);
      return;
    }

    // Find the selected facilitator's name
    const selectedFacilitator = facilitators.find(f => f.id === selectedPersonId);
    const facilitatorName = selectedFacilitator ? selectedFacilitator.name : "Unknown";

    // Save selections to sessionStorage
    sessionStorage.setItem(`assign_facilitator_speaker_${id}_person_id`, selectedPersonId);
    sessionStorage.setItem(`assign_facilitator_speaker_${id}_person_name`, facilitatorName);
    sessionStorage.setItem(`assign_facilitator_speaker_${id}_hours`, estimatedHours);
    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 Facilitator"
        stepSubtitle="Select a facilitator 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 Facilitator"
          description="Select a facilitator based on certifications and availability"
          className="mb-6"
        >
          {/* Info about filtered facilitators */}
          {errors.filteredInfo && (
            <Alert variant="info" icon={ExclamationTriangleIcon} className="mb-4">
              <p className="font-semibold mb-1">Some Facilitators Not Shown</p>
              <p>{errors.filteredInfo}</p>
            </Alert>
          )}

          {/* Count display */}
          {!isLoadingFacilitators && facilitators.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">
                {facilitators.length} facilitator{facilitators.length !== 1 ? 's' : ''} available with hourly rates set
              </p>
            </div>
          )}

          {isLoadingFacilitators ? (
            <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 facilitators...</p>
              </div>
            </div>
          ) : errors.facilitators ? (
            <Alert variant="error" icon={ExclamationTriangleIcon}>
              <p className="font-semibold mb-2">Error Loading Facilitators</p>
              <p>{errors.facilitators}</p>
            </Alert>
          ) : facilitators.length === 0 ? (
            <Alert variant="warning" icon={ExclamationTriangleIcon}>
              <p className="font-semibold mb-2">No Available Facilitators</p>
              <p>
                No facilitators with hourly rates set match the required certifications for this event.
                Please ensure facilitators 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">
                {facilitators.map((facilitator) => (
                  <div
                    key={facilitator.id}
                    className={`p-4 cursor-pointer transition-all rounded-lg border-2 ${
                      selectedPersonId === facilitator.id
                        ? "ring-2 ring-primary-600 bg-primary-50 border-primary-600"
                        : `hover:${getThemeClasses("bg-disabled")} ${getThemeClasses("border-secondary")}`
                    }`}
                    onClick={() => setSelectedPersonId(facilitator.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")}`}>
                            {facilitator.name}
                          </h3>
                          {selectedPersonId === facilitator.id && (
                            <CheckCircleIcon className="h-6 w-6 text-primary-600" />
                          )}
                          {facilitator.isAway && (
                            <Badge variant="warning">Away</Badge>
                          )}
                        </div>

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

                        {facilitator.certifications && facilitator.certifications.length > 0 && (
                          <div className="mt-3">
                            <p className={`text-xs font-medium ${getThemeClasses("text-primary")} mb-1`}>Certifications:</p>
                            <div className="flex flex-wrap gap-1">
                              {facilitator.certifications.map((cert) => (
                                <Badge key={cert.id} variant="info" size="sm">
                                  {cert.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">
                            ${facilitator.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")}`}>
                            {facilitator.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;
                // Allow only positive numbers with decimals
                if (value === "" || /^\d*\.?\d*$/.test(value)) {
                  setEstimatedHours(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 facilitator selection is based on certifications that match
            the event requirements. Make sure to verify availability before proceeding.
          </p>
        </Alert>
      </StaffWizardFormStep>
    </UIXThemeProvider>
  );
}

export default AdminTaskItemAssignFacilitatorOrSpeakerStep3FacilitatorPage;