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

import React, { useState, useEffect, useRef } from "react";
import { useParams, useNavigate } from "react-router";
import {
  ClipboardDocumentListIcon,
  HomeIcon,
  ExclamationTriangleIcon,
  CurrencyDollarIcon,
} from "@heroicons/react/24/outline";
import {
  Breadcrumb,
  Button,
  Card,
  Alert,
  LoadingSpinner,
  useUIXTheme,
  UIXThemeProvider,
  Textarea,
} from "../../../../components/UIX";
import { useTaskManager, useAccountManager } from "../../../../services/Services";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

function AdminTaskItemPayFacilitatorOrSpeakerForEventContractPage() {
  const { tid } = useParams();
  const navigate = useNavigate();
  const taskManager = useTaskManager();
  const accountManager = useAccountManager();
  const { getThemeClasses } = useUIXTheme();

  // State
  const [taskItem, setTaskItem] = useState(null);
  const [userProfile, setUserProfile] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState({});
  const errorRef = useRef(null);

  // Only "Additional Comments" is editable
  const [additionalComments, setAdditionalComments] = useState("");

  // Scroll to error when it appears
  useEffect(() => {
    if (errors.general && errorRef.current) {
      errorRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  }, [errors.general]);

  // Load task item details and user profile
  useEffect(() => {
    if (tid) {
      loadTaskItemAndProfile();
    }
  }, [tid]);

  const loadTaskItemAndProfile = async () => {
    try {
      setIsLoading(true);
      setErrors({});

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

      // Fetch the task item (contains all event contract and review data)
      const taskResponse = await taskManager.getTaskDetail(tid, onUnauthorized);
      setTaskItem(taskResponse);

      // Get user profile from account storage
      const profile = accountManager.accountStorage.getProfileFromCache();
      setUserProfile(profile);
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error loading task item:", error);
      }
      setErrors({
        general: "Failed to load task item. Please try again.",
      });
    } finally {
      setIsLoading(false);
    }
  };

  // Pre-fill additional comments when taskItem and userProfile load
  useEffect(() => {
    if (taskItem && userProfile && !additionalComments) {
      const today = new Date().toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });

      const varianceCost = getVarianceCost();
      const varianceCostText =
        varianceCost >= 0
          ? `$${varianceCost.toLocaleString("en-US", {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}`
          : `-$${Math.abs(varianceCost).toLocaleString("en-US", {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}`;

      // Get event contract ID (check for undefined/null, not falsy, since 0 is invalid but should still show)
      // Note: Backend sends snake_case but humps library converts to camelCase
      const contractId = taskItem.eventContractPublicId !== undefined && taskItem.eventContractPublicId !== null
        ? taskItem.eventContractPublicId
        : "N/A";

      // Get username from profile
      const username = userProfile.name || "Unknown User";

      const prefilledComment = `Event Contract #${contractId} ready for payment and approved by ${username} with variance of ${varianceCostText} on ${today}.`;

      setAdditionalComments(prefilledComment);
    }
  }, [taskItem, userProfile]);

  const handleSubmitPayment = async () => {
    try {
      setIsSubmitting(true);
      setErrors({});

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

      // Prepare payment approval data
      const paymentData = {
        taskItemId: taskItem.id,
        comments: additionalComments.trim(),
      };

      if (import.meta.env.DEV) {
        console.log("Submitting payment approval:", paymentData);
      }

      // Call API to approve payment
      await taskManager.payEventContract(paymentData, onUnauthorized);

      if (import.meta.env.DEV) {
        console.log("Payment approval submitted successfully");
      }

      // Navigate back to task list with success message
      navigate("/admin/tasks?success=payment_approved");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error submitting payment approval:", error);
      }

      const formatFieldName = (fieldName) => {
        return fieldName
          .replace(/_/g, " ")
          .replace(/([A-Z])/g, " $1")
          .toLowerCase()
          .replace(/^./, (str) => str.toUpperCase());
      };

      // Handle specific field errors with user-friendly messages
      if (error.taskItemId) {
        setErrors({
          general: `Missing Task Item\n\nThe task item ID is required.\n\nPlease try again or contact support if the problem persists.`
        });
      } else if (error.comments) {
        setErrors({
          general: `Missing Comments\n\nPayment approval comments are required.\n\nPlease add comments explaining the payment approval decision.`
        });
      } else if (error && typeof error === "object" && !error.message && !error.general) {
        // Handle validation errors with multiple fields
        const errorFields = Object.keys(error);
        if (errorFields.length > 0) {
          const errorMessages = errorFields
            .map((field) => `• ${formatFieldName(field)}: ${error[field]}`)
            .join("\n");
          setErrors({
            general: `Validation Errors\n\nThe following fields have errors:\n\n${errorMessages}\n\nPlease correct these errors and try again.`
          });
        } else {
          setErrors({
            general: "Unexpected Error\n\nPlease try again. If the problem persists, contact support."
          });
        }
      } else if (error.message) {
        setErrors({ general: error.message });
      } else if (error.general) {
        setErrors(error);
      } else {
        setErrors({
          general: "Unexpected Error\n\nFailed to submit payment approval. Please try again."
        });
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  // Calculate derived values
  const getHourlyRate = () => {
    if (!taskItem) return 0;
    return (
      taskItem.facilitatorHourlySalaryDesired ||
      taskItem.speakerHourlySalaryDesired ||
      0
    );
  };

  const getEstimatedHours = () => {
    if (!taskItem) return 0;
    const hours = taskItem.eventContractEstimatedContractHours;
    if (hours === undefined || hours === null) return 0;
    return typeof hours === "number" ? hours : parseFloat(hours) || 0;
  };

  const getEstimatedTotalCost = () => {
    const hours = getEstimatedHours();
    const rate = getHourlyRate();
    return hours * rate;
  };

  const getActualFacilitationOrSpeakerCost = () => {
    if (!taskItem) return 0;
    const cost = taskItem.eventContractActualFacilitationOrSpeakerCost;
    if (cost === undefined || cost === null) return 0;
    return typeof cost === "number" ? cost : parseFloat(cost) || 0;
  };

  const getActualTotalCost = () => {
    if (!taskItem) return 0;
    const cost = taskItem.eventContractActualTotalCost;
    if (cost === undefined || cost === null) return 0;
    return typeof cost === "number" ? cost : parseFloat(cost) || 0;
  };

  const getVarianceHours = () => {
    if (!taskItem) return 0;
    const variance = taskItem.eventContractVarianceHours;
    if (variance === undefined || variance === null) return 0;
    return typeof variance === "number" ? variance : parseFloat(variance) || 0;
  };

  const getVarianceCost = () => {
    if (!taskItem) return 0;
    const variance = taskItem.eventContractVarianceCost;
    if (variance === undefined || variance === null) return 0;
    return typeof variance === "number" ? variance : parseFloat(variance) || 0;
  };

  // Calculate actual hours from the facilitation/speaker cost and hourly rate
  const getActualHours = () => {
    const cost = getActualFacilitationOrSpeakerCost();
    const rate = getHourlyRate();
    if (rate === 0) return 0;
    return cost / rate;
  };

  // Calculate individual cost breakdowns from total
  // Note: Individual breakdowns (travel, supplies, other) are not stored separately
  // They are only available in the total actual cost
  const getOtherCostsTotal = () => {
    const totalCost = getActualTotalCost();
    const facilitationCost = getActualFacilitationOrSpeakerCost();
    return totalCost - facilitationCost;
  };

  // Breadcrumb items
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Task Items",
      to: "/admin/tasks",
      icon: ClipboardDocumentListIcon,
    },
    {
      label: "Pay Facilitator/Speaker",
      icon: CurrencyDollarIcon,
      isActive: true,
    },
  ];

  if (isLoading) {
    return (
      <UIXThemeProvider>
        <div className="min-h-screen flex items-center justify-center">
          <LoadingSpinner size="lg" />
        </div>
      </UIXThemeProvider>
    );
  }

  return (
    <UIXThemeProvider>
      <div className={`min-h-screen ${getThemeClasses("bg-primary")}`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          {/* Breadcrumb */}
          <Breadcrumb items={breadcrumbItems} />

          {/* Header */}
          <div className="mt-6 mb-8">
            <h1
              className={`text-3xl font-bold ${getThemeClasses("text-primary")}`}
            >
              Pay Facilitator/Speaker for Event Contract
            </h1>
            <p className={`mt-2 ${getThemeClasses("text-secondary")}`}>
              Review contract details and approve payment
            </p>
          </div>

          {/* Error Alert */}
          {errors.general && (
            <div ref={errorRef} className="mb-6">
              <Alert variant="error">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <ExclamationTriangleIcon className="h-5 w-5 text-red-400" />
                  </div>
                  <div className="ml-3 flex-1">
                    <h3 className="text-sm font-medium text-red-800">
                      Operation Failed
                    </h3>
                    <div className="mt-2 text-sm text-red-700">
                      <p className="whitespace-pre-wrap">{errors.general}</p>
                    </div>
                  </div>
                </div>
              </Alert>
            </div>
          )}

          {/* Contract Details */}
          {taskItem && (
            <>
              {/* Main Contract Information Card */}
              <Card className="mb-6">
                <div className="p-6">
                  <h2
                    className={`text-xl font-semibold mb-6 ${getThemeClasses("text-primary")}`}
                  >
                    Contract Information
                  </h2>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* Event Title */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Event Title
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.eventName || "-"}
                      </p>
                    </div>

                    {/* Event Date */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Event Date
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.eventEndDateTime
                          ? formatDateForDisplay(taskItem.eventEndDateTime)
                          : "-"}
                      </p>
                    </div>

                    {/* Event Location */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Event Location
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.eventContractLocationNotes || "-"}
                      </p>
                    </div>

                    {/* Org Short Name */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Organization Short Name
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.organizationShortName || "-"}
                      </p>
                    </div>

                    {/* Div Short Name */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Division Short Name
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.divisionShortName || "-"}
                      </p>
                    </div>

                    {/* Contact Name */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Contact Name
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.eventContractContactName || "-"}
                      </p>
                    </div>

                    {/* Facilitator/Speaker Name */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        {taskItem.facilitatorName
                          ? "Facilitator Name"
                          : "Speaker Name"}
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.facilitatorName ||
                          taskItem.speakerName ||
                          "-"}
                      </p>
                    </div>
                  </div>

                  {/* Event Contract Certifications & Skills */}
                  {(taskItem.eventContractCertifications?.length > 0 ||
                    taskItem.eventContractSkillSets?.length > 0) && (
                    <>
                      <div className={`border-t ${getThemeClasses("border-secondary")} my-6`}></div>
                      <div className="space-y-4">
                        {/* Event Contract Certifications */}
                        {taskItem.eventContractCertifications?.length > 0 && (
                          <div>
                            <label
                              className={`block text-sm font-medium mb-2 ${getThemeClasses("text-secondary")}`}
                            >
                              Event Contract Certifications
                            </label>
                            <div className="flex flex-wrap gap-2">
                              {taskItem.eventContractCertifications.map(
                                (cert) => (
                                  <span
                                    key={cert.id}
                                    className="inline-flex items-center px-3 py-1 rounded-full text-sm bg-blue-100 text-blue-800"
                                  >
                                    {cert.name}
                                  </span>
                                )
                              )}
                            </div>
                          </div>
                        )}

                        {/* Event Contract Skills */}
                        {taskItem.eventContractSkillSets?.length > 0 && (
                          <div>
                            <label
                              className={`block text-sm font-medium mb-2 ${getThemeClasses("text-secondary")}`}
                            >
                              Event Contract Skills
                            </label>
                            <div className="flex flex-wrap gap-2">
                              {taskItem.eventContractSkillSets.map((skill) => (
                                <span
                                  key={skill.id}
                                  className="inline-flex items-center px-3 py-1 rounded-full text-sm bg-green-100 text-green-800"
                                >
                                  {skill.category}
                                  {skill.subCategory
                                    ? ` - ${skill.subCategory}`
                                    : ""}
                                </span>
                              ))}
                            </div>
                          </div>
                        )}
                      </div>
                    </>
                  )}
                </div>
              </Card>

              {/* Dividing Line */}
              <div className={`border-t-2 ${getThemeClasses("border-secondary")} my-8`}></div>

              {/* Estimated Costs Section */}
              <Card className="mb-6">
                <div className="p-6">
                  <h2
                    className={`text-xl font-semibold mb-6 ${getThemeClasses("text-primary")}`}
                  >
                    Estimated Costs
                  </h2>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* (A) Estimated Hours */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        (A) Estimated Hours
                      </label>
                      <p
                        className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}
                      >
                        {getEstimatedHours() > 0
                          ? `${getEstimatedHours()} hours`
                          : "-"}
                      </p>
                      <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                        Hours specified during event contract creation
                      </p>
                    </div>

                    {/* Facilitator/Speaker Hourly Rate */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Facilitator/Speaker Hourly Rate
                      </label>
                      <p
                        className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}
                      >
                        {getHourlyRate() > 0
                          ? `$${getHourlyRate().toLocaleString()}/hour`
                          : "-"}
                      </p>
                      <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                        From facilitator/speaker profile
                      </p>
                    </div>
                  </div>

                  {/* Divider */}
                  <div className={`border-t ${getThemeClasses("border-secondary")} my-6`}></div>

                  {/* (B) Total Estimated Cost */}
                  <div className={`${getThemeClasses("bg-disabled")} p-4 rounded-lg`}>
                    <div className="flex justify-between items-center">
                      <div>
                        <label
                          className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                        >
                          (B) Total Estimated Cost
                        </label>
                        <p className={`text-xs ${getThemeClasses("text-muted")}`}>
                          Estimated Hours × Hourly Rate
                        </p>
                      </div>
                      <div className="text-right">
                        <p
                          className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}
                        >
                          {getEstimatedTotalCost() > 0
                            ? `$${getEstimatedTotalCost().toLocaleString(
                                "en-US",
                                {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                }
                              )}`
                            : "-"}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>

              {/* Dividing Line */}
              <div className={`border-t-2 ${getThemeClasses("border-secondary")} my-8`}></div>

              {/* Actual Costs Section */}
              <Card className="mb-6">
                <div className="p-6">
                  <h2
                    className={`text-xl font-semibold mb-6 ${getThemeClasses("text-primary")}`}
                  >
                    Actual Costs
                  </h2>

                  <div className="space-y-6">
                    {/* (a) Actual Hours */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div>
                        <label
                          className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                        >
                          (a) Actual Hours
                        </label>
                        <p
                          className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}
                        >
                          {getActualHours() > 0
                            ? `${getActualHours()} hours`
                            : "-"}
                        </p>
                        <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                          From previous review task
                        </p>
                      </div>

                      {/* (b) Actual Facilitation/Speaking Cost */}
                      <div>
                        <label
                          className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                        >
                          (b) Actual Facilitation/Speaking Cost
                        </label>
                        <p
                          className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}
                        >
                          {getActualFacilitationOrSpeakerCost() > 0
                            ? `$${getActualFacilitationOrSpeakerCost().toLocaleString(
                                "en-US",
                                {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                }
                              )}`
                            : "-"}
                        </p>
                        <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                          Actual Hours × Hourly Rate
                        </p>
                      </div>
                    </div>

                    {/* (c) Other Costs (Travel + Supplies + Other) */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        (c) Other Costs (Travel + Supplies + Other)
                      </label>
                      <p
                        className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}
                      >
                        $
                        {getOtherCostsTotal().toLocaleString("en-US", {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2,
                        })}
                      </p>
                      <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                        Calculated from actual total cost
                      </p>
                    </div>

                    {/* Divider */}
                    <div className={`border-t ${getThemeClasses("border-secondary")} my-6`}></div>

                    {/* (d) Actual Total Contract Cost */}
                    <div className="bg-blue-50 p-4 rounded-lg">
                      <div className="flex justify-between items-center">
                        <div>
                          <label
                            className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                          >
                            (d) Actual Total Contract Cost
                          </label>
                          <p className={`text-xs ${getThemeClasses("text-muted")}`}>
                            Sum of all actual costs
                          </p>
                        </div>
                        <div className="text-right">
                          <p
                            className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}
                          >
                            {getActualTotalCost() > 0
                              ? `$${getActualTotalCost().toLocaleString(
                                  "en-US",
                                  {
                                    minimumFractionDigits: 2,
                                    maximumFractionDigits: 2,
                                  }
                                )}`
                              : "-"}
                          </p>
                        </div>
                      </div>
                    </div>

                    {/* Variance Section */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      {/* (e) Variance (Hours) */}
                      <div className={`${getThemeClasses("bg-disabled")} p-4 rounded-lg border ${getThemeClasses("border-secondary")}`}>
                        <label
                          className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                        >
                          (e) Variance (Hours)
                        </label>
                        <p
                          className={`text-lg font-semibold ${
                            getVarianceHours() >= 0
                              ? "text-green-600"
                              : "text-red-600"
                          }`}
                        >
                          {getActualHours() > 0
                            ? `${getVarianceHours() >= 0 ? "+" : ""}${getVarianceHours().toFixed(2)} hours`
                            : "-"}
                        </p>
                        <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                          Estimated Hours - Actual Hours
                        </p>
                      </div>

                      {/* (f) Variance (Cost) */}
                      <div className={`${getThemeClasses("bg-disabled")} p-4 rounded-lg border ${getThemeClasses("border-secondary")}`}>
                        <label
                          className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                        >
                          (f) Variance (Cost)
                        </label>
                        <p
                          className={`text-lg font-semibold ${
                            getVarianceCost() >= 0
                              ? "text-green-600"
                              : "text-red-600"
                          }`}
                        >
                          {getActualHours() > 0
                            ? `${getVarianceCost() >= 0 ? "+" : ""}$${getVarianceCost().toLocaleString(
                                "en-US",
                                {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                }
                              )}`
                            : "-"}
                        </p>
                        <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                          Estimated Total Cost - Actual Total Cost
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>

              {/* Contract Review Comments */}
              <Card className="mb-6">
                <div className="p-6">
                  <h2
                    className={`text-xl font-semibold mb-4 ${getThemeClasses("text-primary")}`}
                  >
                    Contract Review Comments
                  </h2>
                  <div className={`${getThemeClasses("bg-disabled")} p-4 rounded-lg border ${getThemeClasses("border-secondary")}`}>
                    <p className={`${getThemeClasses("text-primary")}`}>
                      {taskItem.eventContractReviewComment || "-"}
                    </p>
                  </div>
                  <p className={`text-xs ${getThemeClasses("text-muted")} mt-2`}>
                    From previous review task
                  </p>
                </div>
              </Card>

              {/* Additional Comments - Editable */}
              <Card className="mb-6">
                <div className="p-6">
                  <Textarea
                    label="Additional Comments"
                    placeholder="Enter additional payment approval comments..."
                    value={additionalComments}
                    onChange={setAdditionalComments}
                    required={true}
                    error={errors.additionalComments}
                    rows={4}
                    helperText="Additional notes for payment approval"
                  />
                </div>
              </Card>

              {/* Information Label */}
              <Alert variant="info" className="mb-6">
                <span>
                  This contract has been reviewed by a team member and is ready
                  for payment to facilitator/speaker with the data indicated
                  above.
                </span>
              </Alert>

              {/* Action Buttons */}
              <div className="flex justify-end gap-3">
                <Button
                  variant="secondary"
                  onClick={() => navigate("/admin/tasks")}
                  disabled={isSubmitting}
                >
                  Back to Task Items
                </Button>
                <Button
                  variant="primary"
                  onClick={handleSubmitPayment}
                  disabled={isSubmitting}
                  loading={isSubmitting}
                >
                  {isSubmitting ? "Submitting..." : "Approve Payment"}
                </Button>
              </div>
            </>
          )}

          {/* No Task Item Found */}
          {!isLoading && !taskItem && (
            <Card>
              <div className="p-6">
                <Alert variant="warning" className="mb-6">
                  <ExclamationTriangleIcon className="w-5 h-5" />
                  <span>No task item details available.</span>
                </Alert>

                <div className="flex justify-end">
                  <Button
                    variant="secondary"
                    onClick={() => navigate("/admin/tasks")}
                  >
                    Back to Task Items
                  </Button>
                </div>
              </div>
            </Card>
          )}
        </div>
      </div>
    </UIXThemeProvider>
  );
}

export default AdminTaskItemPayFacilitatorOrSpeakerForEventContractPage;
