// File Path: monorepo/web/frontend/src/pages/Admin/TaskItem/CreateEventOrder/Page.jsx

import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router";
import {
  ClipboardDocumentListIcon,
  HomeIcon,
  ExclamationTriangleIcon,
  CalendarIcon,
  ClockIcon,
  MapPinIcon,
  UserGroupIcon,
  DocumentTextIcon,
  TagIcon,
  AcademicCapIcon,
  CpuChipIcon,
  ShieldCheckIcon,
  FolderIcon,
} from "@heroicons/react/24/outline";
import {
  Breadcrumb,
  Button,
  Card,
  Loading,
  Alert,
  useUIXTheme,
  UIXThemeProvider,
} from "../../../../components/UIX";
import {
  useTaskManager,
  useEventManager,
  useEventOrderWizardStorage,
} from "../../../../services/Services";

// 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="flex items-start">
      <Icon className={`w-5 h-5 mr-3 mt-0.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
      <div className="flex-1">
        <span className={`font-medium block text-sm ${getThemeClasses("text-muted")} mb-2`}>
          {label}
        </span>
        <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>
    </div>
  );
};

function AdminTaskItemCreateEventOrderPage() {
  const navigate = useNavigate();
  const { id: taskId } = useParams();
  const { getThemeClasses } = useUIXTheme();
  const taskManager = useTaskManager();
  const eventManager = useEventManager();
  const wizardStorage = useEventOrderWizardStorage();

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [taskData, setTaskData] = useState(null);
  const [eventData, setEventData] = useState(null);

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

  // Load task and event details on mount
  useEffect(() => {
    const loadTaskAndEvent = async () => {
      try {
        setLoading(true);
        setError(null);

        // Fetch task details
        const task = await taskManager.getTaskDetail(taskId, onUnauthorized);
        setTaskData(task);

        // Check if task has event information
        if (!task.eventId) {
          setError("This task is not associated with an event.");
          setLoading(false);
          return;
        }

        // Fetch event details
        const event = await eventManager.getEventDetail(
          task.eventId,
          onUnauthorized,
        );
        setEventData(event);

        setLoading(false);
      } catch (err) {
        if (import.meta.env.DEV) {
          console.error("Error loading task and event:", err);
        }
        setError(
          err?.message ||
            "Failed to load task or event details. Please try again.",
        );
        setLoading(false);
      }
    };

    if (taskId) {
      loadTaskAndEvent();
    } else {
      setError("No task ID provided.");
      setLoading(false);
    }
  }, [taskId, taskManager, eventManager]);

  // Handle create event order button click
  const handleCreateEventOrder = () => {
    // Validate we have required data
    if (!eventData) {
      setError("Event data is missing. Cannot proceed.");
      return;
    }

    // Clear any existing wizard data first
    wizardStorage.clearWizardData();

    // Store event in wizard storage
    wizardStorage.setEvent(eventData);

    if (import.meta.env.DEV) {
      console.log("Stored event data:", eventData);
    }

    // Redirect to step-2 (customer search) since event is already selected
    navigate("/admin/event-orders/add/step-2-search");
  };

  // Show loading state
  if (loading) {
    return (
      <UIXThemeProvider>
        <div
          className={`min-h-screen ${getThemeClasses("bg-gradient-primary")}`}
        >
          <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
            <Card className="shadow-xl">
              <div className="p-6 sm:p-8 text-center">
                <Loading size="lg" text="Loading task and event details..." />
              </div>
            </Card>
          </div>
        </div>
      </UIXThemeProvider>
    );
  }

  // Show error state
  if (error) {
    return (
      <UIXThemeProvider>
        <div
          className={`min-h-screen ${getThemeClasses("bg-gradient-primary")}`}
        >
          <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
            {/* Breadcrumb */}
            <Breadcrumb
              items={[
                {
                  label: "Dashboard",
                  to: "/admin/dashboard",
                  icon: HomeIcon,
                },
                {
                  label: "Task Items",
                  to: "/admin/tasks",
                  icon: ClipboardDocumentListIcon,
                },
                {
                  label: "Create Event Order Task Item",
                  icon: ClipboardDocumentListIcon,
                  isActive: true,
                },
              ]}
            />

            <Card className="shadow-xl mt-6">
              <div className="p-6 sm:p-8 text-center">
                <ExclamationTriangleIcon className="mx-auto h-12 w-12 text-red-400 mb-4" />
                <h3
                  className={`text-lg font-medium mb-2 ${getThemeClasses("text-primary")}`}
                >
                  Error Loading Task
                </h3>
                <Alert type="error" className="mb-6">
                  {error}
                </Alert>
                <div className="flex justify-center gap-3">
                  <Button
                    variant="secondary"
                    onClick={() => navigate("/admin/tasks")}
                  >
                    Back to Tasks
                  </Button>
                  <Button
                    variant="primary"
                    onClick={() => window.location.reload()}
                  >
                    Retry
                  </Button>
                </div>
              </div>
            </Card>
          </div>
        </div>
      </UIXThemeProvider>
    );
  }

  return (
    <UIXThemeProvider>
      <div className={`min-h-screen ${getThemeClasses("bg-gradient-primary")}`}>
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
          {/* Breadcrumb */}
          <Breadcrumb
            items={[
              {
                label: "Dashboard",
                to: "/admin/dashboard",
                icon: HomeIcon,
              },
              {
                label: "Task Items",
                to: "/admin/tasks",
                icon: ClipboardDocumentListIcon,
              },
              {
                label: "Create Event Order Task Item",
                icon: ClipboardDocumentListIcon,
                isActive: true,
              },
            ]}
          />

          {/* Main Content */}
          <Card className="shadow-xl mt-6">
            <div className="p-6 sm:p-8">
              {/* Header */}
              <div className="mb-8">
                <div className="flex items-center mb-4">
                  <div
                    className={`p-3 rounded-2xl shadow-lg mr-4 ${getThemeClasses("bg-gradient-secondary")}`}
                  >
                    <ClipboardDocumentListIcon className="h-8 w-8 text-white" />
                  </div>
                  <div>
                    <h1
                      className={`text-2xl sm:text-3xl font-bold ${getThemeClasses("text-primary")}`}
                    >
                      Create Event Order Task
                    </h1>
                    <p
                      className={`mt-1 text-sm ${getThemeClasses("text-secondary")}`}
                    >
                      Task notification for event order creation
                    </p>
                  </div>
                </div>
              </div>

              {/* Task Description */}
              <div className="py-8">
                <div
                  className={`bg-blue-50 dark:bg-blue-900/20 border-l-4 border-blue-500 p-6 rounded-r-lg mb-6`}
                >
                  <h3
                    className={`text-lg font-semibold mb-2 ${getThemeClasses("text-primary")}`}
                  >
                    Task Assignment
                  </h3>
                  <p
                    className={`text-base ${getThemeClasses("text-secondary")} mb-4`}
                  >
                    This is a task notification to inform you that you need to
                    create an Event Order for the following event. You will need
                    to select a customer in the next step.
                  </p>

                  {eventData && (
                    <div
                      className={`mt-4 p-5 rounded-lg border-2 ${getThemeClasses("bg-secondary")} border-blue-200 dark:border-blue-700`}
                    >
                      <h4
                        className={`font-semibold text-lg ${getThemeClasses("text-primary")} mb-4 flex items-center`}
                      >
                        <ClipboardDocumentListIcon className="w-5 h-5 mr-2" />
                        Event Details
                      </h4>
                      <div
                        className={`space-y-3 ${getThemeClasses("text-secondary")}`}
                      >
                        <div className="flex items-start">
                          <TagIcon className={`w-5 h-5 mr-3 mt-0.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
                          <div className="flex-1">
                            <span className={`font-medium block text-sm ${getThemeClasses("text-muted")}`}>
                              Event Name
                            </span>
                            <span className="text-base">
                              {eventData.eventName || eventData.name}
                            </span>
                          </div>
                        </div>
                        {eventData.startDate && (
                          <div className="flex items-start">
                            <CalendarIcon className={`w-5 h-5 mr-3 mt-0.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
                            <div className="flex-1">
                              <span className={`font-medium block text-sm ${getThemeClasses("text-muted")}`}>
                                Start Date
                              </span>
                              <span className="text-base">
                                {new Date(
                                  eventData.startDate,
                                ).toLocaleDateString()}
                              </span>
                            </div>
                          </div>
                        )}
                        {(eventData.startTime || eventData.endTime) && (
                          <div className="flex items-start">
                            <ClockIcon className={`w-5 h-5 mr-3 mt-0.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
                            <div className="flex-1">
                              <span className={`font-medium block text-sm ${getThemeClasses("text-muted")}`}>
                                Time
                              </span>
                              <span className="text-base">
                                {eventData.startTime && eventData.endTime
                                  ? `${eventData.startTime} - ${eventData.endTime}`
                                  : eventData.startTime || eventData.endTime}
                              </span>
                            </div>
                          </div>
                        )}
                        {eventData.type && (
                          <div className="flex items-start">
                            <TagIcon className={`w-5 h-5 mr-3 mt-0.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
                            <div className="flex-1">
                              <span className={`font-medium block text-sm ${getThemeClasses("text-muted")}`}>
                                Event Type
                              </span>
                              <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
                                {eventData.type === 1
                                  ? "Conference"
                                  : eventData.type === 2
                                    ? "Onsite"
                                    : eventData.type === 3
                                      ? "Offsite"
                                      : eventData.type === 4
                                        ? "Virtual"
                                        : "Unknown"}
                              </span>
                            </div>
                          </div>
                        )}
                        {eventData.location && (
                          <div className="flex items-start">
                            <MapPinIcon className={`w-5 h-5 mr-3 mt-0.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
                            <div className="flex-1">
                              <span className={`font-medium block text-sm ${getThemeClasses("text-muted")}`}>
                                Location
                              </span>
                              <span className="text-base">
                                {eventData.location}
                              </span>
                            </div>
                          </div>
                        )}
                        {eventData.attendeeCapacity > 0 && (
                          <div className="flex items-start">
                            <UserGroupIcon className={`w-5 h-5 mr-3 mt-0.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
                            <div className="flex-1">
                              <span className={`font-medium block text-sm ${getThemeClasses("text-muted")}`}>
                                Capacity
                              </span>
                              <span className="text-base">
                                {eventData.attendeeCapacity} attendees
                              </span>
                            </div>
                          </div>
                        )}
                        {eventData.description && (
                          <div className="flex items-start">
                            <DocumentTextIcon className={`w-5 h-5 mr-3 mt-0.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
                            <div className="flex-1">
                              <span className={`font-medium block text-sm ${getThemeClasses("text-muted")}`}>
                                Description
                              </span>
                              <span className="text-base">
                                {eventData.description}
                              </span>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  )}

                  {/* Additional Event Information from Task Data */}
                  {taskData && (
                    <div
                      className={`mt-4 p-5 rounded-lg border-2 ${getThemeClasses("bg-secondary")} border-green-200 dark:border-green-700`}
                    >
                      <h4
                        className={`font-semibold text-lg ${getThemeClasses("text-primary")} mb-4 flex items-center`}
                      >
                        <FolderIcon className="w-5 h-5 mr-2" />
                        Additional Event Information
                      </h4>
                      <div
                        className={`space-y-4 ${getThemeClasses("text-secondary")}`}
                      >
                        {/* Event Category */}
                        {taskData.eventCategoryName && (
                          <div className="flex items-start">
                            <FolderIcon className={`w-5 h-5 mr-3 mt-0.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
                            <div className="flex-1">
                              <span className={`font-medium block text-sm ${getThemeClasses("text-muted")}`}>
                                Event Category
                              </span>
                              <div className="mt-1">
                                <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">
                                  {taskData.eventCategoryName}
                                </span>
                                {taskData.eventCategoryDescription && (
                                  <p className={`text-sm ${getThemeClasses("text-muted")} mt-2`}>
                                    {taskData.eventCategoryDescription}
                                  </p>
                                )}
                              </div>
                            </div>
                          </div>
                        )}

                        {/* Event Tags */}
                        <BadgeList
                          items={taskData.eventTags}
                          icon={TagIcon}
                          label="Event Tags"
                        />

                        {/* Event Skill Sets */}
                        <BadgeList
                          items={taskData.eventSkillSets}
                          icon={CpuChipIcon}
                          label="Required Skill Sets"
                        />

                        {/* Event Certifications */}
                        <BadgeList
                          items={taskData.eventCertifications}
                          icon={AcademicCapIcon}
                          label="Required Certifications"
                        />

                        {/* Event Specializations */}
                        <BadgeList
                          items={taskData.eventSpecializations}
                          icon={ShieldCheckIcon}
                          label="Required Specializations"
                        />
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* Action Buttons */}
              <div className="flex flex-col sm:flex-row gap-4 pt-6">
                <Button
                  type="button"
                  variant="primary"
                  size="lg"
                  onClick={handleCreateEventOrder}
                  disabled={!eventData}
                  className="w-full sm:w-auto"
                >
                  Continue to Customer Selection
                </Button>
                <Button
                  type="button"
                  variant="secondary"
                  size="lg"
                  onClick={() => navigate("/admin/tasks")}
                  className="w-full sm:w-auto"
                >
                  Back to Tasks
                </Button>
              </div>

              {/* Help Text */}
              <div className={`mt-6 p-4 ${getThemeClasses("bg-disabled")} rounded-lg`}>
                <p
                  className={`text-sm ${getThemeClasses("text-secondary")} mb-2`}
                >
                  <strong>Next Step:</strong> After clicking "Continue to
                  Customer Selection", you will be taken to search for and
                  select a customer for this event order.
                </p>
                {taskData &&
                  (taskData.eventSkillSets?.length > 0 ||
                    taskData.eventCertifications?.length > 0 ||
                    taskData.eventSpecializations?.length > 0) && (
                    <p
                      className={`text-sm ${getThemeClasses("text-secondary")} mt-2`}
                    >
                      <strong>Note:</strong> The event requires specific skill
                      sets, certifications, or specializations. Please keep
                      these requirements in mind when processing this order.
                    </p>
                  )}
              </div>
            </div>
          </Card>
        </div>
      </div>
    </UIXThemeProvider>
  );
}

export default AdminTaskItemCreateEventOrderPage;
