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

import React from "react";
import { useNavigate } from "react-router";
import {
  ClipboardDocumentListIcon,
  HomeIcon,
  ClockIcon,
  UserIcon,
  BuildingOffice2Icon,
  CalendarIcon,
  CheckCircleIcon,
  MagnifyingGlassIcon,
  BanknotesIcon,
  ClipboardDocumentCheckIcon,
  ArchiveBoxIcon,
  DocumentTextIcon,
  ClipboardIcon,
} from "@heroicons/react/24/outline";
import {
  UniversalListPage,
  Badge,
  useUIXTheme,
  Button,
} from "../../../../components/UIX";
import { PAGE_SIZE_OPTIONS } from "../../../../constants/FieldOptions";
import {
  TASK_ITEM_STATUS,
  TASK_ITEM_STATUS_OPTIONS,
  TASK_ITEM_TYPE,
  TASK_ITEM_TYPE_OPTIONS,
  TASK_SORT_OPTIONS,
  TASK_PAGINATION,
} from "../../../../constants/Task";
import { useTaskManager } from "../../../../services/Services";

function AdminTaskItemListPage() {
  const navigate = useNavigate();
  const taskManager = useTaskManager();
  const { getThemeClasses } = useUIXTheme();

  // Task type labels map
  const TASK_TYPE_LABELS = {
    [TASK_ITEM_TYPE.CLOSE_EVENT]: "Close Event",
    [TASK_ITEM_TYPE.ASSIGN_FACILITATOR_OR_SPEAKER_TO_EVENT]:
      "Assign Facilitator/Speaker",
    [TASK_ITEM_TYPE.CREATE_EVENT_ORDER]: "Create Event Order",
    [TASK_ITEM_TYPE.CREATE_EVENT_CONTRACT]: "Create Event Contract",
    [TASK_ITEM_TYPE.CLOSE_EVENT_CONTRACT]: "Close Event Contract",
    [TASK_ITEM_TYPE.EVENT_CONTRACT_REVIEW]: "Review Event Contract",
    [TASK_ITEM_TYPE.PAY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]:
      "Pay Facilitator/Speaker for Event Contract",
    [TASK_ITEM_TYPE.SURVEY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]:
      "Survey Facilitator/Speaker for Event Contract",
    [TASK_ITEM_TYPE.CLOSE_EVENT_ORDER]: "Close Event Order",
    [TASK_ITEM_TYPE.REVIEW_EVENT_ORDER]: "Review Event Order",
    [TASK_ITEM_TYPE.COLLECT_PAYMENT_FOR_EVENT_ORDER]:
      "Collect Payment for Event Order",
    [TASK_ITEM_TYPE.SURVEY_CLIENT_FOR_EVENT_ORDER]:
      "Survey Client for Event Order",
  };

  // Get badge component for task type
  const getTypeBadge = (type) => {
    const variantMap = {
      [TASK_ITEM_TYPE.CLOSE_EVENT]: "primary",
      [TASK_ITEM_TYPE.ASSIGN_FACILITATOR_OR_SPEAKER_TO_EVENT]: "warning",
      [TASK_ITEM_TYPE.CREATE_EVENT_ORDER]: "info",
      [TASK_ITEM_TYPE.CREATE_EVENT_CONTRACT]: "success",
      [TASK_ITEM_TYPE.CLOSE_EVENT_CONTRACT]: "primary",
      [TASK_ITEM_TYPE.EVENT_CONTRACT_REVIEW]: "secondary",
      [TASK_ITEM_TYPE.PAY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]: "success",
      [TASK_ITEM_TYPE.SURVEY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]: "warning",
      [TASK_ITEM_TYPE.CLOSE_EVENT_ORDER]: "primary",
      [TASK_ITEM_TYPE.REVIEW_EVENT_ORDER]: "secondary",
      [TASK_ITEM_TYPE.COLLECT_PAYMENT_FOR_EVENT_ORDER]: "success",
      [TASK_ITEM_TYPE.SURVEY_CLIENT_FOR_EVENT_ORDER]: "warning",
    };
    const variant = variantMap[type] || "default";

    return (
      <Badge variant={variant} size="sm">
        {TASK_TYPE_LABELS[type] || "Unknown"}
      </Badge>
    );
  };

  // Get badge component for task status
  const getStatusBadge = (taskItem) => {
    const variantMap = {
      [TASK_ITEM_STATUS.ACTIVE]: "success", // Green for active tasks
      [TASK_ITEM_STATUS.ARCHIVED]: "secondary", // Gray for archived tasks
      [TASK_ITEM_STATUS.CLOSED]: "info", // Blue for closed/completed tasks
      [TASK_ITEM_STATUS.PENDING]: "warning", // Yellow for pending tasks
    };
    const variant = variantMap[taskItem.status] || "default";

    const statusLabels = {
      [TASK_ITEM_STATUS.ACTIVE]: "Active",
      [TASK_ITEM_STATUS.ARCHIVED]: "Archived",
      [TASK_ITEM_STATUS.CLOSED]: "Closed",
      [TASK_ITEM_STATUS.PENDING]: "Pending",
    };

    return (
      <Badge variant={variant} size="sm">
        {statusLabels[taskItem.status] || "Unknown"}
      </Badge>
    );
  };

  // Format date helper
  const formatDate = (dateString) => {
    if (!dateString) return "N/A";
    try {
      return new Date(dateString).toLocaleDateString("en-US", {
        year: "numeric",
        month: "short",
        day: "numeric",
      });
    } catch (error) {
      return "Invalid Date";
    }
  };

  // Build params function for the API
  const buildParams = (params) => {
    const {
      pageSize = TASK_PAGINATION.DEFAULT_PAGE_SIZE,
      currentCursor,
      sortBy,
      sortOrder,
      status,
      type,
      searchQuery,
    } = params || {};

    const apiParams = {
      page_size: String(pageSize),
    };

    // Add cursor for pagination
    if (currentCursor) {
      apiParams.cursor = currentCursor;
    }

    // Add sorting
    if (sortBy && sortOrder) {
      apiParams.sort_field = sortBy;
      apiParams.sort_order = sortOrder;
    }

    // Add filters
    if (status && status !== "0" && status !== "") {
      apiParams.status = parseInt(status);
    }

    if (type && type !== "0" && type !== "") {
      apiParams.type = parseInt(type);
    }

    if (searchQuery && searchQuery.trim()) {
      apiParams.search = searchQuery.trim();
    }

    return apiParams;
  };

  // Fetch data function
  const fetchData = async (params, onUnauthorized, forceRefresh) => {
    try {
      const taskParams = buildParams(params);
      if (import.meta.env.DEV) {
        console.log(
          "TaskItem List: Calling taskManager.getTasks with params:",
          taskParams,
        );
      }

      const response = await taskManager.getTasks(
        taskParams,
        onUnauthorized,
        forceRefresh,
      );

      if (import.meta.env.DEV) {
        console.log("TaskItem List: Received response:", response);
      }

      return {
        results: response.results || [],
        count: response.count || 0,
        nextCursor: response.nextCursor || "",
        hasNextPage: response.hasNextPage || false,
      };
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("TaskItem List: Error fetching tasks:", error);
      }
      throw error;
    }
  };

  // Get role-based person label
  const getPersonLabel = (taskItem) => {
    if (taskItem.facilitatorName) {
      return { label: "Facilitator", name: taskItem.facilitatorName };
    }
    if (taskItem.speakerName) {
      return { label: "Speaker", name: taskItem.speakerName };
    }
    return null;
  };

  // Get contract/order reference
  const getReference = (taskItem) => {
    if (taskItem.eventContractPublicID) {
      return `Contract #${taskItem.eventContractPublicID}`;
    }
    if (taskItem.eventOrderPublicID) {
      return `Order #${taskItem.eventOrderPublicID}`;
    }
    return null;
  };

  // Get urgency level
  const getUrgency = (taskItem) => {
    if (taskItem.status !== TASK_ITEM_STATUS.ACTIVE) return null;
    if (!taskItem.eventEndDateTime) return null;

    const now = new Date();
    const eventDate = new Date(taskItem.eventEndDateTime);
    const daysUntil = Math.ceil((eventDate - now) / (1000 * 60 * 60 * 24));

    if (daysUntil < 0) return { level: "overdue", label: "Overdue", color: "red" };
    if (daysUntil === 0) return { level: "today", label: "Due Today", color: "orange" };
    if (daysUntil <= 3) return { level: "urgent", label: `${daysUntil} days`, color: "yellow" };
    if (daysUntil <= 7) return { level: "soon", label: `${daysUntil} days`, color: "blue" };
    return null;
  };

  // Get task-specific context
  const getTaskContext = (taskItem) => {
    switch (taskItem.type) {
      case TASK_ITEM_TYPE.CLOSE_EVENT:
        return {
          icon: CalendarIcon,
          title: "Close Event",
          subtitle: "Mark event as completed or cancelled",
        };
      case TASK_ITEM_TYPE.ASSIGN_FACILITATOR_OR_SPEAKER_TO_EVENT:
        const certCount = taskItem.eventContractCertifications?.length || 0;
        const skillCount = taskItem.eventContractSkillSets?.length || 0;
        return {
          icon: UserIcon,
          title: "Assign Resource",
          subtitle: certCount > 0 ? `Requires ${certCount} cert${certCount > 1 ? 's' : ''}` : skillCount > 0 ? `Requires ${skillCount} skill${skillCount > 1 ? 's' : ''}` : "No specific requirements",
        };
      case TASK_ITEM_TYPE.CREATE_EVENT_ORDER:
        return {
          icon: DocumentTextIcon,
          title: "Create Order",
          subtitle: "Generate purchase order for event",
        };
      case TASK_ITEM_TYPE.CREATE_EVENT_CONTRACT:
        return {
          icon: ClipboardDocumentListIcon,
          title: "Create Contract",
          subtitle: "Generate service contract",
        };
      case TASK_ITEM_TYPE.CLOSE_EVENT_CONTRACT:
        return {
          icon: CheckCircleIcon,
          title: "Close Contract",
          subtitle: "Finalize contract execution",
        };
      case TASK_ITEM_TYPE.EVENT_CONTRACT_REVIEW:
        const estimatedCost = taskItem.eventContractEstimatedContractHours *
          (taskItem.facilitatorHourlySalaryDesired || taskItem.speakerHourlySalaryDesired || 0);
        return {
          icon: MagnifyingGlassIcon,
          title: "Review Contract",
          subtitle: estimatedCost > 0 ? `Est. Cost: $${estimatedCost.toLocaleString()}` : "Review costs and hours",
        };
      case TASK_ITEM_TYPE.PAY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT:
        const totalCost = taskItem.eventContractActualTotalCost || 0;
        const variance = taskItem.eventContractVarianceCost || 0;
        const varianceText = variance !== 0
          ? ` (${variance > 0 ? '+' : ''}$${Math.abs(variance).toLocaleString()} variance)`
          : '';
        return {
          icon: BanknotesIcon,
          title: "Process Payment",
          subtitle: totalCost > 0 ? `Pay $${totalCost.toLocaleString()}${varianceText}` : "Payment pending",
          amount: totalCost,
          variance: variance,
        };
      case TASK_ITEM_TYPE.SURVEY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT:
        const facilitatorOrSpeaker = taskItem.facilitatorName || taskItem.speakerName || "resource";
        return {
          icon: ClipboardDocumentCheckIcon,
          title: "Survey",
          subtitle: `Collect feedback from ${facilitatorOrSpeaker}`,
        };
      case TASK_ITEM_TYPE.CLOSE_EVENT_ORDER:
        return {
          icon: ArchiveBoxIcon,
          title: "Close Order",
          subtitle: "Finalize event order",
        };
      case TASK_ITEM_TYPE.REVIEW_EVENT_ORDER:
        const orderTotal = taskItem.eventOrderTotalCost || 0;
        return {
          icon: MagnifyingGlassIcon,
          title: "Review Order",
          subtitle: orderTotal > 0 ? `Review order ($${orderTotal.toLocaleString()})` : "Review order details",
        };
      case TASK_ITEM_TYPE.COLLECT_PAYMENT_FOR_EVENT_ORDER:
        const paymentAmount = taskItem.eventOrderAmountDue || taskItem.eventOrderTotalCost || 0;
        return {
          icon: BanknotesIcon,
          title: "Collect Payment",
          subtitle: paymentAmount > 0 ? `Collect $${paymentAmount.toLocaleString()}` : "Payment collection pending",
        };
      case TASK_ITEM_TYPE.SURVEY_CLIENT_FOR_EVENT_ORDER:
        const clientName = taskItem.customerName || "client";
        return {
          icon: ClipboardDocumentCheckIcon,
          title: "Client Survey",
          subtitle: `Collect feedback from ${clientName}`,
        };
      default:
        return {
          icon: ClipboardIcon,
          title: "Task",
          subtitle: "",
        };
    }
  };

  // Check if task is overdue (legacy - keeping for compatibility)
  const isOverdue = (taskItem) => {
    const urgency = getUrgency(taskItem);
    return urgency?.level === "overdue";
  };

  // Custom grid item renderer
  const renderGridItem = (taskItem, navigate) => {
    const person = getPersonLabel(taskItem);
    const reference = getReference(taskItem);
    const urgency = getUrgency(taskItem);
    const taskContext = getTaskContext(taskItem);

    // Urgency border colors
    const getBorderClass = () => {
      if (!urgency) return "";
      switch (urgency.color) {
        case "red": return "border-l-4 border-l-red-500";
        case "orange": return "border-l-4 border-l-orange-500";
        case "yellow": return "border-l-4 border-l-yellow-500";
        case "blue": return "border-l-4 border-l-blue-500";
        default: return "";
      }
    };

    // Urgency badge
    const getUrgencyBadge = () => {
      if (!urgency) return null;
      const colorClasses = {
        red: "bg-red-100 text-red-800 border-red-200",
        orange: "bg-orange-100 text-orange-800 border-orange-200",
        yellow: "bg-yellow-100 text-yellow-800 border-yellow-200",
        blue: "bg-blue-100 text-blue-800 border-blue-200",
      };
      return (
        <span className={`text-xs font-semibold px-2 py-1 rounded border flex items-center gap-1 ${colorClasses[urgency.color]}`}>
          <ClockIcon className="w-3 h-3" /> {urgency.label}
        </span>
      );
    };

    return (
      <div
        key={taskItem.id}
        className={`${getThemeClasses("bg-card")} border ${getThemeClasses("card-border")} rounded-lg shadow-sm hover:shadow-lg transition-all ${getBorderClass()}`}
      >
        <div className="p-5">
          {/* Urgency + Status Header */}
          <div className="flex items-center justify-between mb-3">
            {getUrgencyBadge()}
            {getStatusBadge(taskItem)}
          </div>

          {/* Task Context with Icon */}
          <div className="mb-3">
            <div className="flex items-start gap-2">
              <taskContext.icon className={`w-6 h-6 mt-0.5 flex-shrink-0 ${getThemeClasses("text-primary")}`} />
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                  <h4 className={`text-sm font-semibold ${getThemeClasses("text-primary")}`}>
                    {taskContext.title}
                  </h4>
                  {reference && (
                    <span className={`text-xs ${getThemeClasses("text-muted")} ${getThemeClasses("bg-disabled")} px-2 py-0.5 rounded`}>
                      {reference}
                    </span>
                  )}
                </div>
                {taskContext.subtitle && (
                  <p className={`text-xs ${getThemeClasses("text-secondary")} mt-0.5`}>
                    {taskContext.subtitle}
                  </p>
                )}
              </div>
            </div>
          </div>

          {/* Event Name */}
          <div className="mb-3">
            <h3 className={`text-base font-semibold ${getThemeClasses("text-primary")} line-clamp-2`}>
              {taskItem.eventName || `Event #${taskItem.eventPublicID || taskItem.id}`}
            </h3>
          </div>

          {/* Context Grid: Org/Div + Person */}
          <div className="grid grid-cols-2 gap-3 mb-3">
            {/* Organization & Division */}
            <div className="min-w-0">
              <div className="flex items-start gap-1.5">
                <BuildingOffice2Icon className={`w-3.5 h-3.5 mt-0.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
                <div className="min-w-0 flex-1">
                  <p className={`text-xs ${getThemeClasses("text-muted")}`}>Organization</p>
                  <p className={`text-sm font-medium ${getThemeClasses("text-primary")} truncate`}>
                    {taskItem.customerOrganizationShortName || taskItem.customerOrganizationName || taskItem.organizationShortName || taskItem.organizationName || "-"}
                  </p>
                  {(taskItem.customerDivisionShortName || taskItem.customerDivisionName || taskItem.divisionShortName || taskItem.divisionName) && (
                    <p className={`text-xs ${getThemeClasses("text-muted")} truncate`}>
                      {taskItem.customerDivisionShortName || taskItem.customerDivisionName || taskItem.divisionShortName || taskItem.divisionName}
                    </p>
                  )}
                </div>
              </div>
            </div>

            {/* Assigned Person */}
            {person && (
              <div className="min-w-0">
                <div className="flex items-start gap-1.5">
                  <UserIcon className={`w-3.5 h-3.5 mt-0.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
                  <div className="min-w-0 flex-1">
                    <p className={`text-xs ${getThemeClasses("text-muted")}`}>{person.label}</p>
                    <p className={`text-sm font-medium ${getThemeClasses("text-primary")} truncate`}>
                      {person.name}
                    </p>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Event Date + Pending Activation */}
          <div className="space-y-1.5 mb-4">
            {taskItem.eventEndDateTime && (
              <div className="flex items-center gap-1.5 text-sm">
                <CalendarIcon className={`w-3.5 h-3.5 flex-shrink-0 ${urgency?.color === 'red' || urgency?.color === 'orange' ? 'text-' + urgency.color + '-500' : getThemeClasses("text-muted")}`} />
                <span className={urgency?.color === 'red' || urgency?.color === 'orange' ? 'text-' + urgency.color + '-600 font-medium' : getThemeClasses("text-secondary")}>
                  Event: {formatDate(taskItem.eventEndDateTime)}
                </span>
              </div>
            )}
            {taskItem.activateAt && taskItem.status === TASK_ITEM_STATUS.PENDING && (
              <div className="flex items-center gap-1.5 text-sm">
                <ClockIcon className={`w-3.5 h-3.5 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
                <span className={`${getThemeClasses("text-secondary")}`}>
                  Activates: {formatDate(taskItem.activateAt)}
                </span>
              </div>
            )}
          </div>

          {/* Action buttons for Close Event tasks that are Active or Pending */}
          {taskItem.type === TASK_ITEM_TYPE.CLOSE_EVENT &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="primary"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(`/admin/task/${taskItem.id}/close-event`);
                  }}
                  className="w-full"
                >
                  Close Event
                </Button>
              </div>
            )}

          {/* Action buttons for Assign Facilitator/Speaker tasks that are Active or Pending */}
          {taskItem.type ===
            TASK_ITEM_TYPE.ASSIGN_FACILITATOR_OR_SPEAKER_TO_EVENT &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="warning"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(
                      `/admin/task/${taskItem.id}/assign-facilitator-speaker/step-1`,
                    );
                  }}
                  className="w-full"
                >
                  Assign Facilitator/Speaker
                </Button>
              </div>
            )}

          {/* Action buttons for Create Event Order tasks that are Active or Pending */}
          {taskItem.type === TASK_ITEM_TYPE.CREATE_EVENT_ORDER &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="info"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(`/admin/task/${taskItem.id}/create-event-order`);
                  }}
                  className="w-full"
                >
                  Create Event Order
                </Button>
              </div>
            )}

          {/* Action buttons for Create Event Contract tasks that are Active or Pending */}
          {taskItem.type === TASK_ITEM_TYPE.CREATE_EVENT_CONTRACT &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="success"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(`/admin/task/${taskItem.id}/create-event-contract`);
                  }}
                  className="w-full"
                >
                  Create Event Contract
                </Button>
              </div>
            )}

          {/* Action buttons for Close Event Contract tasks that are Active or Pending */}
          {taskItem.type === TASK_ITEM_TYPE.CLOSE_EVENT_CONTRACT &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="primary"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(`/admin/task/${taskItem.id}/close-event-contract`);
                  }}
                  className="w-full"
                >
                  Close Event Contract
                </Button>
              </div>
            )}

          {/* Action buttons for Review Event Contract tasks that are Active or Pending */}
          {taskItem.type === TASK_ITEM_TYPE.EVENT_CONTRACT_REVIEW &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(`/admin/task/${taskItem.id}/review-event-contract`);
                  }}
                  className="w-full"
                >
                  Review Event Contract
                </Button>
              </div>
            )}

          {/* Action buttons for Pay Facilitator/Speaker for Event Contract tasks that are Active or Pending */}
          {taskItem.type ===
            TASK_ITEM_TYPE.PAY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="success"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(
                      `/admin/task/${taskItem.id}/pay-facilitator-or-speaker-for-event-contract`,
                    );
                  }}
                  className="w-full"
                >
                  Process Payment
                </Button>
              </div>
            )}

          {/* Action buttons for Survey Facilitator/Speaker for Event Contract tasks that are Active or Pending */}
          {taskItem.type ===
            TASK_ITEM_TYPE.SURVEY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(
                      `/admin/task/${taskItem.id}/survey-event-contract`,
                    );
                  }}
                  className="w-full"
                >
                  Complete Survey
                </Button>
              </div>
            )}

          {/* Action buttons for Close Event Order tasks that are Active or Pending */}
          {taskItem.type === TASK_ITEM_TYPE.CLOSE_EVENT_ORDER &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="primary"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(`/admin/task/${taskItem.id}/close-event-order`);
                  }}
                  className="w-full"
                >
                  Close Event Order
                </Button>
              </div>
            )}

          {/* Action buttons for Review Event Order tasks that are Active or Pending */}
          {taskItem.type === TASK_ITEM_TYPE.REVIEW_EVENT_ORDER &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(`/admin/task/${taskItem.id}/review-event-order`);
                  }}
                  className="w-full"
                >
                  Review Event Order
                </Button>
              </div>
            )}

          {/* Action buttons for Collect Payment for Event Order tasks that are Active or Pending */}
          {taskItem.type === TASK_ITEM_TYPE.COLLECT_PAYMENT_FOR_EVENT_ORDER &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="success"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(
                      `/admin/task/${taskItem.id}/collect-payment-for-event-order`,
                    );
                  }}
                  className="w-full"
                >
                  Collect Payment
                </Button>
              </div>
            )}

          {/* Action buttons for Survey Client for Event Order tasks that are Active or Pending */}
          {taskItem.type === TASK_ITEM_TYPE.SURVEY_CLIENT_FOR_EVENT_ORDER &&
            (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
              taskItem.status === TASK_ITEM_STATUS.PENDING) && (
              <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                <Button
                  variant="warning"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(
                      `/admin/task/${taskItem.id}/client-survey-for-event-order`,
                    );
                  }}
                  className="w-full"
                >
                  Complete Survey
                </Button>
              </div>
            )}
        </div>
      </div>
    );
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Task & Event",
      accessor: "eventName",
      render: (value, taskItem) => {
        const taskContext = getTaskContext(taskItem);
        const reference = getReference(taskItem);
        const urgency = getUrgency(taskItem);

        return (
          <div className="flex items-start gap-2">
            <taskContext.icon className={`w-5 h-5 mt-0.5 flex-shrink-0 ${getThemeClasses("text-primary")}`} />
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-1">
                <span className={`font-medium text-sm ${getThemeClasses("text-primary")}`}>
                  {taskContext.title}
                </span>
                {reference && (
                  <span className={`text-xs ${getThemeClasses("text-muted")} ${getThemeClasses("bg-disabled")} px-2 py-0.5 rounded`}>
                    {reference}
                  </span>
                )}
              </div>
              {taskContext.subtitle && (
                <p className={`text-xs ${getThemeClasses("text-secondary")} mb-1`}>
                  {taskContext.subtitle}
                </p>
              )}
              <p className={`text-sm font-medium ${urgency?.color === 'red' || urgency?.color === 'orange' ? 'text-' + urgency.color + '-600' : getThemeClasses("text-primary")} truncate`}>
                {value || `Event #${taskItem.eventPublicID || taskItem.id}`}
              </p>
            </div>
          </div>
        );
      },
    },
    {
      header: "Organization / Division",
      accessor: "customerOrganizationShortName",
      render: (value, taskItem) => {
        // Prioritize customer organization, then fall back to general organization
        const orgName = taskItem.customerOrganizationShortName || taskItem.customerOrganizationName || taskItem.organizationShortName || taskItem.organizationName || "-";
        const divName = taskItem.customerDivisionShortName || taskItem.customerDivisionName || taskItem.divisionShortName || taskItem.divisionName;

        return (
          <div className="flex items-center">
            <BuildingOffice2Icon className={`w-4 h-4 mr-2 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
            <div className="truncate">
              <div className="font-medium">{orgName}</div>
              {divName && (
                <div className={`text-sm ${getThemeClasses("text-muted")}`}>
                  {divName}
                </div>
              )}
            </div>
          </div>
        );
      },
    },
    {
      header: "Assigned To",
      accessor: "facilitatorName",
      render: (value, taskItem) => {
        const person = getPersonLabel(taskItem);
        if (!person) return <span className={getThemeClasses("text-muted")}>-</span>;
        return (
          <div className="flex items-center">
            <UserIcon className={`w-4 h-4 mr-2 flex-shrink-0 ${getThemeClasses("text-muted")}`} />
            <div className="truncate">
              <div className={`text-xs ${getThemeClasses("text-muted")}`}>{person.label}</div>
              <div className="font-medium">{person.name}</div>
            </div>
          </div>
        );
      },
    },
    {
      header: "Urgency & Date",
      accessor: "eventEndDateTime",
      render: (date, taskItem) => {
        const urgency = getUrgency(taskItem);

        // Urgency badge colors
        const getUrgencyBadgeColors = () => {
          if (!urgency) return null;
          const colorClasses = {
            red: "bg-red-100 text-red-800 border-red-200",
            orange: "bg-orange-100 text-orange-800 border-orange-200",
            yellow: "bg-yellow-100 text-yellow-800 border-yellow-200",
            blue: "bg-blue-100 text-blue-800 border-blue-200",
          };
          return colorClasses[urgency.color];
        };

        return (
          <div className="space-y-1">
            {urgency && (
              <span className={`inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded border ${getUrgencyBadgeColors()}`}>
                <ClockIcon className="w-3 h-3" /> {urgency.label}
              </span>
            )}
            <div className="flex items-center">
              <CalendarIcon className={`w-3.5 h-3.5 mr-1.5 ${urgency?.color === 'red' || urgency?.color === 'orange' ? 'text-' + urgency.color + '-500' : getThemeClasses("text-muted")}`} />
              <span className={`text-sm ${urgency?.color === 'red' || urgency?.color === 'orange' ? 'text-' + urgency.color + '-600 font-medium' : ''}`}>
                {formatDate(date)}
              </span>
            </div>
          </div>
        );
      },
    },
    {
      header: "Status",
      accessor: "status",
      render: (status, taskItem) => (
        <div className="space-y-1">
          {getStatusBadge(taskItem)}
          {taskItem.status === TASK_ITEM_STATUS.PENDING && taskItem.activateAt && (
            <div className={`text-xs ${getThemeClasses("text-muted")} flex items-center mt-1`}>
              <ClockIcon className="w-3 h-3 mr-1" />
              {formatDate(taskItem.activateAt)}
            </div>
          )}
        </div>
      ),
    },
    {
      header: "Actions",
      align: "right",
      render: (value, taskItem) => {
        // Show Close Event action for Close Event tasks that are Active or Pending
        if (
          taskItem.type === TASK_ITEM_TYPE.CLOSE_EVENT &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="primary"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(`/admin/task/${taskItem.id}/close-event`);
              }}
            >
              Close Event
            </Button>
          );
        }
        // Show Assign action for Assign Facilitator/Speaker tasks that are Active or Pending
        if (
          taskItem.type ===
            TASK_ITEM_TYPE.ASSIGN_FACILITATOR_OR_SPEAKER_TO_EVENT &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="warning"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(
                  `/admin/task/${taskItem.id}/assign-facilitator-speaker/step-1`,
                );
              }}
            >
              Assign
            </Button>
          );
        }
        // Show Create Order action for Create Event Order tasks that are Active or Pending
        if (
          taskItem.type === TASK_ITEM_TYPE.CREATE_EVENT_ORDER &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="info"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(`/admin/task/${taskItem.id}/create-event-order`);
              }}
            >
              Create Order
            </Button>
          );
        }
        // Show Create Contract action for Create Event Contract tasks that are Active or Pending
        if (
          taskItem.type === TASK_ITEM_TYPE.CREATE_EVENT_CONTRACT &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="success"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(`/admin/task/${taskItem.id}/create-event-contract`);
              }}
            >
              Create Contract
            </Button>
          );
        }
        // Show Close Event Contract action for Close Event Contract tasks that are Active or Pending
        if (
          taskItem.type === TASK_ITEM_TYPE.CLOSE_EVENT_CONTRACT &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="primary"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(`/admin/task/${taskItem.id}/close-event-contract`);
              }}
            >
              Close Contract
            </Button>
          );
        }
        // Show Review Event Contract action for Review Event Contract tasks that are Active or Pending
        if (
          taskItem.type === TASK_ITEM_TYPE.EVENT_CONTRACT_REVIEW &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="secondary"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(`/admin/task/${taskItem.id}/review-event-contract`);
              }}
            >
              Review Contract
            </Button>
          );
        }
        // Show Process Payment action for Pay Facilitator/Speaker for Event Contract tasks that are Active or Pending
        if (
          taskItem.type ===
            TASK_ITEM_TYPE.PAY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="success"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(
                  `/admin/task/${taskItem.id}/pay-facilitator-or-speaker-for-event-contract`,
                );
              }}
            >
              Process Payment
            </Button>
          );
        }
        // Show Complete Survey action for Survey Facilitator/Speaker for Event Contract tasks that are Active or Pending
        if (
          taskItem.type ===
            TASK_ITEM_TYPE.SURVEY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="secondary"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(
                  `/admin/task/${taskItem.id}/survey-event-contract`,
                );
              }}
            >
              Complete Survey
            </Button>
          );
        }
        // Show Close Event Order action for Close Event Order tasks that are Active or Pending
        if (
          taskItem.type === TASK_ITEM_TYPE.CLOSE_EVENT_ORDER &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="primary"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(`/admin/task/${taskItem.id}/close-event-order`);
              }}
            >
              Close Order
            </Button>
          );
        }
        // Show Review Event Order action for Review Event Order tasks that are Active or Pending
        if (
          taskItem.type === TASK_ITEM_TYPE.REVIEW_EVENT_ORDER &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="secondary"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(`/admin/task/${taskItem.id}/review-event-order`);
              }}
            >
              Review Order
            </Button>
          );
        }
        // Show Collect Payment action for Collect Payment for Event Order tasks that are Active or Pending
        if (
          taskItem.type === TASK_ITEM_TYPE.COLLECT_PAYMENT_FOR_EVENT_ORDER &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="success"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(
                  `/admin/task/${taskItem.id}/collect-payment-for-event-order`,
                );
              }}
            >
              Collect Payment
            </Button>
          );
        }
        // Show Complete Survey action for Survey Client for Event Order tasks that are Active or Pending
        if (
          taskItem.type === TASK_ITEM_TYPE.SURVEY_CLIENT_FOR_EVENT_ORDER &&
          (taskItem.status === TASK_ITEM_STATUS.ACTIVE ||
            taskItem.status === TASK_ITEM_STATUS.PENDING)
        ) {
          return (
            <Button
              variant="warning"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                navigate(
                  `/admin/task/${taskItem.id}/client-survey-for-event-order`,
                );
              }}
            >
              Complete Survey
            </Button>
          );
        }
        return null;
      },
    },
  ];

  // Status filter options (using the constants)
  const statusOptions = TASK_ITEM_STATUS_OPTIONS;

  // Type filter options (using the constants)
  const typeOptions = TASK_ITEM_TYPE_OPTIONS;

  // Sort options - only "created by" sorting for task items
  const sortOptions = [
    { value: "created_at,DESC", label: "Created (Newest → Oldest)" },
    { value: "created_at,ASC", label: "Created (Oldest → Newest)" },
  ];

  // UniversalListPage configuration
  const config = {
    entityName: "Task Item",
    entityNamePlural: "Task Items",
    icon: ClipboardDocumentListIcon,
    title: "Task Item Management",
    subtitle: "View and manage task items across the system",
    // Task item routes - disabled create and search since tasks are system-generated
    routes: {
      search: undefined, // Disabled
      create: undefined, // Disabled - task items are system-generated
      detail: "/admin/task/:id", // Task detail route
    },
    // Explicitly disable create and search features
    showCreateButton: false,
    showSearchButton: false,
    createLabel: undefined,
    searchIcon: undefined,
    createIcon: undefined,
    breadcrumbItems: [
      {
        label: "Dashboard",
        to: "/admin/dashboard",
        icon: HomeIcon,
      },
      {
        label: "Task Items",
        to: "/admin/tasks",
        icon: ClipboardDocumentListIcon,
        isActive: true,
      },
    ],
    columns,
    statusOptions,
    typeOptions,
    sortOptions,
    pageSizeOptions: TASK_PAGINATION.PAGE_SIZE_OPTIONS.map((opt) => ({
      value: opt.value,
      label: opt.label,
    })),
    searchPlaceholder:
      "Search task items by title, description, customer, or facilitator...",
    emptyState: {
      title: "No Task Items Found",
      filterDescription:
        "No task items match your current filters. Try adjusting your search criteria.",
      emptyDescription: "No task items have been created yet. Task items are automatically generated by the system based on events and workflows.",
      actionLabel: undefined, // No action button - tasks are system-generated
      onActionClick: undefined,
      isCreateAction: false,
    },
    fetchData,
    buildParams,
    renderGridItem,
    defaultStatus: "1", // Active tasks
    defaultType: "0", // All types
    defaultSort: "created_at",
    defaultSortOrder: "DESC",
    defaultPageSize: TASK_PAGINATION.DEFAULT_PAGE_SIZE,
    defaultViewType: "grid",
  };

  return <UniversalListPage config={config} />;
}

export default AdminTaskItemListPage;
