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

import React, { useState, useEffect, memo } from "react";
import { useNavigate } from "react-router";
import { useReportManager } from "../../../../services/Services";
import {
  Button,
  EntityReportDetail,
  Input,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  XCircleIcon,
  CalendarIcon,
} from "@heroicons/react/24/outline";

function AdminReport04Page() {
  return (
    <UIXThemeProvider>
      <AdminReport04PageContent />
    </UIXThemeProvider>
  );
}

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

  // Form state
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");

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

  // Load preferences and set default dates on mount
  useEffect(() => {
    // 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]);
  }, []);

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

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

    // 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;
      }

      // Note: As per requirements, no range restrictions on the date range size
    }

    return { errors: newErrors, hasErrors };
  };

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

    // 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(),
      };

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

      await reportManager.downloadReport(
        4, // Report ID for Cancelled 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({
        lastCancelledJobsReport: {
          // Could save date range preferences if needed
        },
      });

      if (import.meta.env.DEV) {
        console.log("AdminReport04Page: Report downloaded successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminReport04Page: 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();

  // Calculate summary statistics from date range
  const getDateRangeSummary = () => {
    if (!fromDate || !toDate) return null;

    const from = new Date(fromDate);
    const to = new Date(toDate);
    const daysDiff = Math.floor((to - from) / (1000 * 60 * 60 * 24)) + 1;

    return {
      days: daysDiff,
      weeks: Math.floor(daysDiff / 7),
      months: Math.floor(daysDiff / 30),
    };
  };

  const dateRangeSummary = getDateRangeSummary();

  return (
    <EntityReportDetail
      reportTitle="Cancelled Jobs Report"
      reportDescription="Generate a report of all cancelled jobs within a date range"
      reportBreadcrumbLabel="Cancelled Jobs"
      icon={XCircleIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report will generate a CSV file containing all cancelled jobs within the specified date range. The dates refer to the assignment date of the work orders. The report includes cancellation reasons and facilitatord details."
      recentDownloads={recentDownloads}
      reportId={4}
      reportType="Cancelled Jobs"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* 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>

        {/* Date Range Summary */}
        {dateRangeSummary && (
          <div className={`rounded-lg p-4 ${getThemeClasses("bg-subtle")}`}>
            <h4 className={`text-sm font-medium mb-2 ${getThemeClasses("text-primary")}`}>
              Date Range Summary
            </h4>
            <div className="grid grid-cols-3 gap-4 text-center">
              <div>
                <p className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>
                  {dateRangeSummary.days}
                </p>
                <p className={`text-xs ${getThemeClasses("text-secondary")}`}>Days</p>
              </div>
              <div>
                <p className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>
                  {dateRangeSummary.weeks}
                </p>
                <p className={`text-xs ${getThemeClasses("text-secondary")}`}>Weeks</p>
              </div>
              <div>
                <p className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>
                  {dateRangeSummary.months}
                </p>
                <p className={`text-xs ${getThemeClasses("text-secondary")}`}>Months</p>
              </div>
            </div>
          </div>
        )}

        {/* 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>
  );
});

AdminReport04PageContent.displayName = "AdminReport04PageContent";

export default AdminReport04Page;
