// File Path: monorepo/web/frontend/src/pages/Admin/TaskItem/CollectPaymentForEventOrder/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 AdminTaskItemCollectPaymentForEventOrderPage() {
  const { id } = 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 (id) {
      loadTaskItemAndProfile();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

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

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

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

      if (import.meta.env.DEV) {
        console.log("CollectPaymentForEventOrder: Task item loaded:", 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 varianceSeats = getVarianceSeats();
      const varianceSeatsText =
        varianceSeats >= 0
          ? `${varianceSeats} seats`
          : `${varianceSeats} seats`;

      // Get event order 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 orderId =
        taskItem.eventOrderPublicId !== undefined &&
        taskItem.eventOrderPublicId !== null
          ? taskItem.eventOrderPublicId
          : "N/A";

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

      const prefilledComment = `Event Order #${orderId} ready for invoicing and approved by ${username} with variance of ${varianceSeatsText} on ${today}.`;

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

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

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

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

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

      // Call API to collect payment for event order
      await taskManager.collectPaymentEventOrder(paymentData, onUnauthorized);

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

      // Navigate back to task list with success message
      navigate("/admin/tasks?success=payment_collected");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error submitting payment collection:", 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 collection. Please try again."
        });
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  // Calculate derived values for Event Order (seats-based)
  const getEstimatedSeats = () => {
    if (!taskItem) return 0;
    // Field name from backend: eventOrderEstimatedNumberOfAttendees
    const seats = taskItem.eventOrderEstimatedNumberOfAttendees;
    if (seats === undefined || seats === null) return 0;
    return typeof seats === "number" ? seats : parseInt(seats) || 0;
  };

  const getActualSeats = () => {
    if (!taskItem) return 0;
    // Field name from backend: eventOrderActualNumberOfAttendees
    const seats = taskItem.eventOrderActualNumberOfAttendees;
    if (seats === undefined || seats === null) return 0;
    return typeof seats === "number" ? seats : parseInt(seats) || 0;
  };

  const getVarianceSeats = () => {
    if (!taskItem) return 0;
    // Field name from backend: eventOrderVarianceOfNumberOfAttendees
    const variance = taskItem.eventOrderVarianceOfNumberOfAttendees;
    if (variance === undefined || variance === null) {
      // Calculate if not provided: Actual - Estimated (matches ReviewEventOrder)
      return getActualSeats() - getEstimatedSeats();
    }
    return typeof variance === "number" ? variance : parseFloat(variance) || 0;
  };

  // Breadcrumb items
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Task Items",
      to: "/admin/tasks",
      icon: ClipboardDocumentListIcon,
    },
    {
      label: "Collect Payment for Event Order",
      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")}`}
            >
              Collect Payment for Event Order
            </h1>
            <p className={`mt-2 ${getThemeClasses("text-secondary")}`}>
              Review event order details and collect payment from client
            </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 Event Order Information Card */}
              <Card className="mb-6">
                <div className="p-6">
                  <h2
                    className={`text-xl font-semibold mb-6 ${getThemeClasses("text-primary")}`}
                  >
                    Event Order 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.eventOrderAdditionalOrderNotes || 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.customerOrganizationShortName || "-"}
                      </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.customerDivisionShortName || "-"}
                      </p>
                    </div>

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

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

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

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

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

                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    {/* Estimated Seats */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Estimated Seats
                      </label>
                      <p
                        className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}
                      >
                        {getEstimatedSeats() > 0
                          ? `${getEstimatedSeats()} seats`
                          : "-"}
                      </p>
                      <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                        Seats ordered during event order creation
                      </p>
                    </div>

                    {/* Actual Seats */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Actual Seats Ordered
                      </label>
                      <p
                        className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}
                      >
                        {getActualSeats() > 0
                          ? `${getActualSeats()} seats`
                          : "-"}
                      </p>
                      <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                        From Event Order &gt; Task &gt; Order Review
                      </p>
                    </div>

                    {/* Variance (Seats) */}
                    <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")}`}
                      >
                        Variance
                      </label>
                      <p
                        className={`text-lg font-semibold ${
                          getVarianceSeats() >= 0
                            ? "text-green-600"
                            : "text-red-600"
                        }`}
                      >
                        {getVarianceSeats() !== 0
                          ? `${getVarianceSeats() >= 0 ? "+" : ""}${getVarianceSeats()} seats`
                          : "0 seats"}
                      </p>
                      <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                        Estimated - Actual (can be negative)
                      </p>
                    </div>
                  </div>
                </div>
              </Card>

              {/* Order Review Comments */}
              <Card className="mb-6">
                <div className="p-6">
                  <h2
                    className={`text-xl font-semibold mb-4 ${getThemeClasses("text-primary")}`}
                  >
                    Comments
                  </h2>
                  <div className={`${getThemeClasses("bg-disabled")} p-4 rounded-lg border ${getThemeClasses("border-secondary")}`}>
                    <p className={`${getThemeClasses("text-primary")}`}>
                      {taskItem.eventOrderReviewComment || "-"}
                    </p>
                  </div>
                  <p className={`text-xs ${getThemeClasses("text-muted")} mt-2`}>
                    Pre-filled with closing comment from Event Order &gt; Task &gt; Order Review
                  </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 order has been reviewed by a team member and is ready to invoice to the client 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..." : "Collect 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 AdminTaskItemCollectPaymentForEventOrderPage;
