// File Path: monorepo/web/frontend/src/pages/Admin/Report/00To09/02Page.jsx

import React, { useState, useEffect, memo } from "react";
import { useNavigate } from "react-router";
import { useReportManager } from "../../../../services/Services";
import { FacilitatorSelect } from "../../../../components/business/selects";
import { ORDER_STATUS_FILTER_OPTIONS } from "../../../../constants/FieldOptions";
import {
  Button,
  EntityReportDetail,
  Select,
  Input,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  UserIcon,
  CalendarIcon,
} from "@heroicons/react/24/outline";

function AdminReport02Page() {
  return (
    <UIXThemeProvider>
      <AdminReport02PageContent />
    </UIXThemeProvider>
  );
}

const AdminReport02PageContent = memo(function AdminReport02PageContent() {
  const navigate = useNavigate();
  const reportManager = useReportManager();
  const { getThemeClasses } = useUIXTheme();

  // Form state
  const [facilitatorID, setFacilitatorID] = useState("");
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");
  const [jobStatus, setJobStatus] = useState("0");

  // UI state
  const [errors, setErrors] = useState({});
  const [warnings, setWarnings] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);

  // Load preferences on mount
  useEffect(() => {
    const preferences = reportManager.getReportPreferences();
    if (preferences?.lastFacilitatorJobsReport) {
      setJobStatus(
        String(preferences.lastFacilitatorJobsReport.jobStatus || 0),
      );
    }

    // Set default dates (last 30 days)
    const today = new Date();
    const thirtyDaysAgo = new Date(today);
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    setToDate(today.toISOString().split("T")[0]);
    setFromDate(thirtyDaysAgo.toISOString().split("T")[0]);
  }, []);

  // Check for date range warnings when dates change
  useEffect(() => {
    if (fromDate && toDate) {
      const from = new Date(fromDate);
      const to = new Date(toDate);
      const daysDiff = Math.floor((to - from) / (1000 * 60 * 60 * 24));

      if (daysDiff > 365) {
        setWarnings((prev) => ({
          ...prev,
          dateRange: `Date range exceeds 1 year (${daysDiff} days). Large date ranges may take longer to process.`,
        }));
      } else {
        setWarnings((prev) => {
          const newWarnings = { ...prev };
          delete newWarnings.dateRange;
          return newWarnings;
        });
      }
    }
  }, [fromDate, toDate]);

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

  // Handle facilitator selection change
  const handleFacilitatorChange = (value) => {
    setFacilitatorID(value);

    // Clear facilitator error if it exists
    if (errors.facilitatorID) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors.facilitatorID;
        return newErrors;
      });
    }
  };

  // Validate form
  const validateForm = () => {
    const newErrors = {};
    let hasErrors = false;

    // Validate facilitator selection
    if (!facilitatorID) {
      newErrors.facilitatorID = "Please select an facilitator";
      hasErrors = true;
    }

    // Validate dates
    if (!fromDate) {
      newErrors.fromDate = "From date is required";
      hasErrors = true;
    }

    if (!toDate) {
      newErrors.toDate = "To date is required";
      hasErrors = true;
    }

    // Check date range
    if (fromDate && toDate) {
      const from = new Date(fromDate);
      const to = new Date(toDate);

      if (from > to) {
        newErrors.toDate = "To date must be after from date";
        hasErrors = true;
      }

      // Check for future dates
      const today = new Date();
      today.setHours(23, 59, 59, 999);

      if (to > today) {
        newErrors.toDate = "To date cannot be in the future";
        hasErrors = true;
      }
    }

    return { errors: newErrors, hasErrors };
  };

  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (import.meta.env.DEV) {
      console.log("AdminReport02Page: Submitting report", {
        facilitatorID,
        fromDate,
        toDate,
        jobStatus,
      });
    }

    // Validate
    const validation = validateForm();
    if (validation.hasErrors) {
      setErrors(validation.errors);
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }

    // Clear errors and start submission
    setErrors({});
    setIsSubmitting(true);
    setShowSuccess(false);

    try {
      // Convert dates to timestamps
      const fromDateObj = new Date(fromDate);
      const toDateObj = new Date(toDate);

      // Download the report using generic downloadReport method
      const params = {
        from_dt: fromDateObj.getTime(),
        to_dt: toDateObj.getTime(),
        state: parseInt(jobStatus) || 0,
        facilitator_id: facilitatorID,
      };

      // Generate filename
      const timestamp = new Date().toISOString().split("T")[0];
      const filename = `facilitator_jobs_report_${timestamp}.csv`;

      await reportManager.downloadReport(
        2, // Report ID for Facilitator Jobs Report
        params,
        filename,
        onUnauthorized,
      );

      // Show success message
      setShowSuccess(true);

      // Hide success message after 5 seconds
      setTimeout(() => {
        setShowSuccess(false);
      }, 5000);

      // Save preferences for next time
      reportManager.saveReportPreferences({
        lastFacilitatorJobsReport: {
          jobStatus,
        },
      });

      if (import.meta.env.DEV) {
        console.log("AdminReport02Page: Report downloaded successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminReport02Page: Error downloading report", error);
      }

      // Handle errors
      if (typeof error === "object" && error !== null) {
        setErrors(error);
      } else {
        setErrors({
          general: "Failed to download report. Please try again.",
        });
      }
      window.scrollTo({ top: 0, behavior: "smooth" });
    } finally {
      setIsSubmitting(false);
    }
  };

  // Get recent downloads from history
  const recentDownloads = reportManager.getReportHistory();

  return (
    <EntityReportDetail
      reportTitle="Facilitator Jobs Report"
      reportDescription="Generate a report of jobs assigned to a specific facilitator"
      reportBreadcrumbLabel="Facilitator Jobs"
      icon={UserIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report will generate a CSV file containing all work orders assigned to the selected facilitator within the specified date range. The dates refer to the assignment date of the work orders."
      recentDownloads={recentDownloads}
      reportId={2}
      reportType="Facilitator Jobs"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Warning Display for Date Range */}
        {warnings.dateRange && (
          <div className={`p-4 rounded-lg ${getThemeClasses("bg-warning-subtle")} ${getThemeClasses("text-warning")}`}>
            <div className="flex items-start">
              <div>
                <p className="font-medium">Warning</p>
                <p className="mt-1 text-sm">{warnings.dateRange}</p>
              </div>
            </div>
          </div>
        )}

        {/* Facilitator Selection Field */}
        <FacilitatorSelect
          value={facilitatorID}
          onChange={handleFacilitatorChange}
          error={errors.facilitatorID}
          required={true}
          label="Select Facilitator"
          helperText="Start typing to search for an facilitator by name"
          onUnauthorized={onUnauthorized}
          placeholder="Please select an facilitator"
          statusFilter={1} // Only show active facilitators
        />

        {/* Date Range Row */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* From Date Field */}
          <Input
            label="From Date"
            name="fromDate"
            type="date"
            value={fromDate}
            onChange={(value) => {
              setFromDate(value);
              if (errors.fromDate) {
                setErrors((prev) => {
                  const newErrors = { ...prev };
                  delete newErrors.fromDate;
                  return newErrors;
                });
              }
            }}
            error={errors.fromDate}
            required
            icon={CalendarIcon}
            helperText="Start date for the report (assignment date)"
          />

          {/* To Date Field */}
          <Input
            label="To Date"
            name="toDate"
            type="date"
            value={toDate}
            onChange={(value) => {
              setToDate(value);
              if (errors.toDate) {
                setErrors((prev) => {
                  const newErrors = { ...prev };
                  delete newErrors.toDate;
                  return newErrors;
                });
              }
            }}
            error={errors.toDate}
            required
            icon={CalendarIcon}
            helperText="End date for the report (assignment date)"
          />
        </div>

        {/* Job Status Field */}
        <Select
          label="Job Status Filter"
          value={jobStatus}
          onChange={(value) => {
            setJobStatus(value);
            if (errors.jobStatus) {
              setErrors((prev) => {
                const newErrors = { ...prev };
                delete newErrors.jobStatus;
                return newErrors;
              });
            }
          }}
          options={ORDER_STATUS_FILTER_OPTIONS.map((opt) => ({
            value: String(opt.value),
            label: opt.label,
          }))}
          error={errors.jobStatus}
          helperText="Filter the report by specific job status or select 'All' for all statuses"
        />

        {/* Form Actions */}
        <div className={`flex flex-col sm:flex-row items-center justify-between pt-6 border-t ${getThemeClasses("border-color")} gap-3`}>
          <Button
            onClick={() => navigate("/admin/reports")}
            variant="secondary"
          >
            Back to Reports
          </Button>
          <Button
            onClick={handleSubmit}
            variant="success"
            disabled={isSubmitting}
            loading={isSubmitting}
            loadingText="Generating..."
          >
            Download Report
          </Button>
        </div>
      </form>
    </EntityReportDetail>
  );
});

AdminReport02PageContent.displayName = "AdminReport02PageContent";

export default AdminReport02Page;
