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

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

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

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

  // Form state
  const [actualSeats, setActualSeats] = useState("");
  const [comments, setComments] = useState("");

  // Get logged-in user's name
  const getUserName = () => {
    if (userProfile) {
      const firstName = userProfile.firstName || "";
      const lastName = userProfile.lastName || "";
      const fullName = `${firstName} ${lastName}`.trim();
      return fullName || "Staff Member";
    }
    return "Staff Member";
  };

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

  // Load user profile on mount
  useEffect(() => {
    const loadUserProfile = async () => {
      try {
        const onUnauthorized = () => navigate("/login?unauthorized=true");
        const profile = await accountManager.getAccountDetail(onUnauthorized);
        setUserProfile(profile);
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Error loading user profile:", error);
        }
      }
    };

    loadUserProfile();
  }, [accountManager, navigate]);

  // Load task item details
  useEffect(() => {
    if (id) {
      loadTaskItem();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

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

      const onUnauthorized = () => navigate("/login?unauthorized=true");
      const taskResponse = await taskManager.getTaskDetail(id, onUnauthorized);
      setTaskItem(taskResponse);
    } 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);
    }
  };

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

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

      // Calculate variance: Actual - Estimated
      const varianceSeats = getVarianceSeats();

      const reviewData = {
        task_item_id: taskItem.id,
        actual_seats_ordered: parseInt(actualSeats) || 0,
        variance_hours: varianceSeats, // Backend expects this field name
        comments: comments.trim(),
      };

      if (import.meta.env.DEV) {
        console.log("ReviewEventOrder: Submitting review data:", reviewData);
      }

      await taskManager.reviewEventOrder(reviewData, onUnauthorized);

      if (import.meta.env.DEV) {
        console.log("ReviewEventOrder: Review submitted successfully");
      }

      navigate("/admin/tasks?success=review_submitted");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("ReviewEventOrder: Error submitting review:", 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.actualSeats || error.actual_seats_ordered) {
        setErrors({
          general: `Missing Actual Seats\n\nThe actual number of seats ordered is a required field.\n\nPlease enter the actual seats purchased for this event order.`
        });
      } else if (error.comments) {
        setErrors({
          general: `Missing Comments\n\nReview comments are required.\n\nPlease add comments summarizing the order review and variance details.`
        });
      } 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 review. Please try again."
        });
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  // Calculate seat variance
  const getEstimatedSeats = () => {
    if (!taskItem) return 0;
    const seats = taskItem.eventOrderEstimatedNumberOfAttendees;
    if (seats === undefined || seats === null) return 0;
    return typeof seats === "number" ? seats : parseInt(seats) || 0;
  };

  const getVarianceSeats = () => {
    const estimated = getEstimatedSeats();
    const actual = parseInt(actualSeats) || 0;
    return actual - estimated;
  };

  // Pre-fill comments when actualSeats changes
  useEffect(() => {
    if (taskItem && actualSeats && parseInt(actualSeats) >= 0) {
      const varianceSeats = getVarianceSeats();
      const today = new Date().toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });

      const prefilledComment = `Order review completed by ${getUserName()} on ${today} with a variance of ${varianceSeats} seats.`;

      if (!comments || comments.includes("Order review completed by")) {
        setComments(prefilledComment);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [taskItem, actualSeats]);

  // Breadcrumb items
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Task Items",
      to: "/admin/tasks",
      icon: ClipboardDocumentListIcon,
    },
    {
      label: "Review Event Order",
      icon: ClipboardDocumentListIcon,
      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-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <Breadcrumb items={breadcrumbItems} />

          <div className="mt-6 mb-8">
            <h1
              className={`text-3xl font-bold ${getThemeClasses("text-primary")}`}
            >
              Review Event Order
            </h1>
            <p className={`mt-2 ${getThemeClasses("text-secondary")}`}>
              Review and approve the event order
            </p>
          </div>

          {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>
          )}

          {taskItem && (
            <Card className="mb-6">
              <div className="p-6 space-y-6">
                {/* Read-only Event & Customer Information */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <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>

                  <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>

                  <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>

                  <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>
                    <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>

                  <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>

                  <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>

                  <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 className={`border-t ${getThemeClasses("border-secondary")} my-6`}></div>

                {/* Seats Section */}
                <div className="space-y-4">
                  <div>
                    <label className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}>
                      Estimated Seats
                    </label>
                    <p className={`text-base font-semibold ${getThemeClasses("text-primary")}`}>
                      {getEstimatedSeats()} seats
                    </p>
                    <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                      Seats ordered during event order creation
                    </p>
                  </div>

                  <div>
                    <Input
                      label="Actual Seats Ordered"
                      type="number"
                      placeholder="Enter actual seats ordered"
                      value={actualSeats}
                      onChange={setActualSeats}
                      required={true}
                      error={errors.actualSeats}
                      helperText="Number of seats actually purchased (mandatory)"
                    />
                  </div>

                  {actualSeats && parseInt(actualSeats) >= 0 && (
                    <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()} seats
                      </p>
                      <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                        Actual Seats - Estimated Seats
                      </p>
                    </div>
                  )}
                </div>

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

                {/* Comments */}
                <div>
                  <Textarea
                    label="Comments"
                    placeholder="Enter review comments..."
                    value={comments}
                    onChange={setComments}
                    required={true}
                    error={errors.comments}
                    rows={4}
                    helperText="Review summary including variance details (mandatory)"
                  />
                </div>

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

          {!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 AdminTaskItemReviewEventOrderPage;
