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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import {
  UIXThemeProvider,
  StaffWizardFormStep,
  FormSection,
  InfoField,
  Alert,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  ClipboardDocumentListIcon,
  UserGroupIcon,
  ExclamationTriangleIcon,
  CalendarIcon,
  MapPinIcon,
  LinkIcon,
  UsersIcon,
  TagIcon,
  AcademicCapIcon,
  CpuChipIcon,
  ShieldCheckIcon,
  FolderIcon,
} from "@heroicons/react/24/outline";
import { useTaskManager } from "../../../../services/Services";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

// Helper component to display badge list
const BadgeList = ({ items, icon: Icon, label }) => {
  const { getThemeClasses } = useUIXTheme();

  if (!items || items.length === 0) return null;

  const getBadgeText = (item) => {
    // For skill sets, combine category and subcategory if available
    if (item.category) {
      return item.subCategory
        ? `${item.category} - ${item.subCategory}`
        : item.category;
    }
    // For other items, use name or text
    return item.name || item.text || "N/A";
  };

  return (
    <div className="mb-4">
      <label className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-2`}>
        {label}
      </label>
      <div className="flex flex-wrap gap-2">
        {items.map((item, index) => (
          <span
            key={item.id || index}
            className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200"
            title={item.description || ""}
          >
            {getBadgeText(item)}
          </span>
        ))}
      </div>
    </div>
  );
};

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

  const [taskItem, setTaskItem] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [errors, setErrors] = useState({});

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

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

  const fetchTaskItem = useCallback(async () => {
    setIsLoading(true);
    setErrors({});

    try {
      const taskResponse = await taskManager.getTaskDetail(id, onUnauthorized);
      if (import.meta.env.DEV) {
        console.log("TaskItem response:", taskResponse);
      }
      setTaskItem(taskResponse);
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error fetching task item:", error);
      }
      setErrors({ message: "Failed to load task item details." });
    } finally {
      setIsLoading(false);
    }
  }, [id, taskManager, navigate]);

  useEffect(() => {
    fetchTaskItem();
  }, [id, fetchTaskItem]);

  // Format time to 12-hour format
  const formatTime = (timeStr) => {
    if (!timeStr) return "";
    const [hours, minutes] = timeStr.split(":");
    const hour = parseInt(hours, 10);
    const ampm = hour >= 12 ? "PM" : "AM";
    const displayHour = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
    return `${displayHour}:${minutes} ${ampm}`;
  };

  // Extract time from datetime string
  const extractTimeFromDateTime = (datetimeStr) => {
    if (!datetimeStr) return "";
    try {
      const date = new Date(datetimeStr);
      const hours = date.getHours();
      const minutes = date.getMinutes();
      const ampm = hours >= 12 ? "PM" : "AM";
      const displayHour = hours === 0 ? 12 : hours > 12 ? hours - 12 : hours;
      const displayMinutes = minutes.toString().padStart(2, "0");
      return `${displayHour}:${displayMinutes} ${ampm}`;
    } catch (error) {
      return "";
    }
  };

  const handleNext = () => {
    // Navigate directly to step-3 based on eventContractRoleType
    // 1 = Facilitator, 2 = Speaker
    if (taskItem?.eventContractRoleType === 1) {
      navigate(`/admin/task/${id}/assign-facilitator-speaker/step-3-facilitator`);
    } else if (taskItem?.eventContractRoleType === 2) {
      navigate(`/admin/task/${id}/assign-facilitator-speaker/step-3-speaker`);
    } else {
      // If no role type is set, default to facilitator
      if (import.meta.env.DEV) {
        console.warn("No eventContractRoleType found, defaulting to facilitator");
      }
      navigate(`/admin/task/${id}/assign-facilitator-speaker/step-3-facilitator`);
    }
  };

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

  return (
    <UIXThemeProvider>
      <StaffWizardFormStep
        wizardSteps={wizardSteps}
        currentStep={1}
        wizardTitle="Assign Facilitator or Speaker"
        wizardIcon={UserGroupIcon}
        stepTitle="Event Details"
        stepSubtitle="Review the event information before proceeding"
        stepIcon={ClipboardDocumentListIcon}
        errors={errors}
        isLoading={isLoading}
        showFormCard={true}
        actionLayout="between"
        contentMaxWidth="4xl"
        showActions={true}
        actions={[
          {
            label: taskItem?.eventContractRoleType === 1
              ? "Next: Select Facilitator"
              : taskItem?.eventContractRoleType === 2
                ? "Next: Select Speaker"
                : "Next: Select Person",
            variant: "primary",
            onClick: handleNext,
            disabled: !taskItem,
          },
        ]}
        onBack={handleCancel}
        onCancel={handleCancel}
        backLabel="Back to Tasks"
        cancelLabel="Cancel"
      >
        {taskItem && (
          <>
            {/* Event Summary Section */}
            <FormSection
              title="Event Summary"
              description="Event details and contract information"
              className="mb-6"
            >
              {/* Title */}
              <div className="mb-4">
                <InfoField
                  label="Event Title"
                  value={taskItem.eventName || "N/A"}
                />
              </div>

              {/* Date/Time */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">
                <InfoField
                  label="Event Date"
                  value={
                    taskItem.eventEndDateTime
                      ? formatDateForDisplay(taskItem.eventEndDateTime)
                      : "N/A"
                  }
                  icon={CalendarIcon}
                />
                <InfoField
                  label="Event Time"
                  value={
                    taskItem.eventEndDateTime
                      ? extractTimeFromDateTime(taskItem.eventEndDateTime)
                      : "Time not specified"
                  }
                  icon={CalendarIcon}
                />
              </div>

              {/* Partner */}
              {taskItem.organizationName && (
                <div className="mb-4">
                  <InfoField
                    label="Partner Organization"
                    value={taskItem.organizationName}
                    icon={UsersIcon}
                  />
                </div>
              )}

              {/* Location Notes from Event Contract */}
              {taskItem.eventContractLocationNotes && (
                <div className="mb-4">
                  <InfoField
                    label="Location Notes"
                    value={taskItem.eventContractLocationNotes}
                    icon={MapPinIcon}
                  />
                </div>
              )}

              {/* Contact Information from Event Contract */}
              {(taskItem.eventContractContactName || taskItem.eventContractContactNumber) && (
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">
                  {taskItem.eventContractContactName && (
                    <InfoField
                      label="Contact Name"
                      value={taskItem.eventContractContactName}
                    />
                  )}
                  {taskItem.eventContractContactNumber && (
                    <InfoField
                      label="Contact Number"
                      value={taskItem.eventContractContactNumber}
                    />
                  )}
                </div>
              )}

              {/* Additional Contact Notes */}
              {taskItem.eventContractAdditionalContactNotes && (
                <div className="mb-4">
                  <InfoField
                    label="Additional Contact Notes"
                    value={taskItem.eventContractAdditionalContactNotes}
                  />
                </div>
              )}

              {/* Estimated Contract Hours */}
              {taskItem.eventContractEstimatedContractHours > 0 && (
                <div className="mb-4">
                  <InfoField
                    label="Estimated Contract Hours"
                    value={`${taskItem.eventContractEstimatedContractHours} hours`}
                  />
                </div>
              )}

              {/* Description */}
              {taskItem.eventDescription && (
                <div className="mt-6">
                  <InfoField
                    label="Event Description"
                    value={taskItem.eventDescription}
                  />
                </div>
              )}
            </FormSection>

            {/* Requirements Section */}
            <FormSection
              title="Event Requirements"
              description="Skills, certifications, and specializations required for this event"
              className="mb-6"
            >
              {/* Event Category */}
              {taskItem.eventCategoryName && (
                <div className="mb-4">
                  <label className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-2`}>
                    <FolderIcon className="inline-block w-4 h-4 mr-1" />
                    Event Category
                  </label>
                  <div>
                    <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200">
                      {taskItem.eventCategoryName}
                    </span>
                    {taskItem.eventCategoryDescription && (
                      <p className={`text-sm ${getThemeClasses("text-muted")} mt-2`}>
                        {taskItem.eventCategoryDescription}
                      </p>
                    )}
                  </div>
                </div>
              )}

              {/* Event Tags */}
              {taskItem.eventTags && taskItem.eventTags.length > 0 && (
                <BadgeList
                  items={taskItem.eventTags}
                  icon={TagIcon}
                  label="Event Tags"
                />
              )}

              {/* Specializations */}
              {taskItem.eventSpecializations && taskItem.eventSpecializations.length > 0 && (
                <BadgeList
                  items={taskItem.eventSpecializations}
                  icon={ShieldCheckIcon}
                  label="Required Specializations"
                />
              )}

              {/* Certifications */}
              {taskItem.eventCertifications && taskItem.eventCertifications.length > 0 && (
                <BadgeList
                  items={taskItem.eventCertifications}
                  icon={AcademicCapIcon}
                  label="Required Certifications"
                />
              )}

              {/* Skill Sets */}
              {taskItem.eventSkillSets && taskItem.eventSkillSets.length > 0 && (
                <BadgeList
                  items={taskItem.eventSkillSets}
                  icon={CpuChipIcon}
                  label="Required Skill Sets"
                />
              )}

              {/* Show message if no requirements */}
              {!taskItem.eventCategoryName &&
                (!taskItem.eventTags || taskItem.eventTags.length === 0) &&
                (!taskItem.eventSpecializations || taskItem.eventSpecializations.length === 0) &&
                (!taskItem.eventCertifications || taskItem.eventCertifications.length === 0) &&
                (!taskItem.eventSkillSets || taskItem.eventSkillSets.length === 0) && (
                  <Alert variant="info">
                    <p>No specific requirements have been set for this event.</p>
                  </Alert>
                )}
            </FormSection>

            {/* Instructions Alert */}
            <Alert variant="info" icon={ExclamationTriangleIcon}>
              <p className="font-semibold mb-2">Next Steps:</p>
              <p className="mb-2">
                In the following steps, you will select whether to assign a facilitator or speaker,
                select the person, provide acceptance details, and submit the assignment.
              </p>
              {(taskItem.eventSkillSets?.length > 0 ||
                taskItem.eventCertifications?.length > 0 ||
                taskItem.eventSpecializations?.length > 0) && (
                <p className="mt-2 pt-2 border-t border-blue-200 dark:border-blue-700">
                  <strong>Important:</strong> This event has specific skill sets, certifications, or
                  specializations requirements. Please ensure the person you select meets these requirements.
                </p>
              )}
            </Alert>
          </>
        )}
      </StaffWizardFormStep>
    </UIXThemeProvider>
  );
}

export default AdminTaskItemAssignFacilitatorOrSpeakerStep1Page;