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

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

function AdminReport06Page() {
  return (
    <UIXThemeProvider>
      <AdminReport06PageContent />
    </UIXThemeProvider>
  );
}

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

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

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

  // Handle form submission
  const handleSubmit = async (e) => {
    if (e) {
      e.preventDefault();
    }

    if (import.meta.env.DEV) {
      console.log("AdminReport06Page: Submitting report");
    }

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

    try {
      // No parameters needed for this report
      const params = {};

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

      await reportManager.downloadReport(
        6, // Report ID for Facilitator Police Check 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({
        lastFacilitatorPoliceCheckReport: {
          lastDownloaded: new Date().toISOString(),
        },
      });

      if (import.meta.env.DEV) {
        console.log("AdminReport06Page: Report downloaded successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminReport06Page: 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 Police Check Report"
      reportDescription="Generate a report of all facilitators' police check status"
      reportBreadcrumbLabel="Facilitator Police Check"
      icon={ShieldCheckIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report will generate a CSV file containing the police check status for all active facilitators. The report includes police check dates, expiration dates, and compliance status to help ensure all facilitators meet safety requirements."
      recentDownloads={recentDownloads}
      reportId={6}
      reportType="Facilitator Police Check"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      {/* Simple Download Section */}
      <div className={`rounded-lg p-6 text-center ${getThemeClasses("bg-subtle")}`}>
        <ShieldCheckIcon className={`w-12 h-12 mx-auto mb-4 ${getThemeClasses("text-accent")}`} />
        <h3 className={`text-lg font-medium mb-2 ${getThemeClasses("text-primary")}`}>
          Generate and Download Report
        </h3>
        <p className={`text-sm mb-6 ${getThemeClasses("text-secondary")}`}>
          There are no fields to choose from. Simply click the button
          below to generate and download the current facilitator police
          check report.
        </p>

        {/* Download Button */}
        <Button
          onClick={handleSubmit}
          variant="success"
          size="lg"
          disabled={isSubmitting}
          loading={isSubmitting}
          loadingText="Generating Report..."
        >
          Download Report
        </Button>
      </div>

      {/* Additional Information */}
      <div className={`mt-6 p-4 rounded-lg ${getThemeClasses("bg-info-subtle")}`}>
        <div className="flex">
          <InformationCircleIcon className={`w-5 h-5 mr-2 flex-shrink-0 ${getThemeClasses("text-info")}`} />
          <div className={`text-sm ${getThemeClasses("text-info")}`}>
            <p className="font-medium mb-1">Quick Tip:</p>
            <p>
              This report is automatically generated with the most
              current data. It includes all active facilitators and
              their police check status as of today's date. Use this
              report for compliance auditing and safety verification.
            </p>
          </div>
        </div>
      </div>

      {/* Navigation Actions */}
      <div className={`flex items-center justify-between pt-6 mt-6 border-t ${getThemeClasses("border-color")}`}>
        <Button
          onClick={() => navigate("/admin/reports")}
          variant="secondary"
        >
          Back to Reports
        </Button>
      </div>
    </EntityReportDetail>
  );
});

AdminReport06PageContent.displayName = "AdminReport06PageContent";

export default AdminReport06Page;
