// File Path: monorepo/web/frontend/src/pages/Admin/Report/00To09/05Page.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 AdminReport05Page() {
  return (
    <UIXThemeProvider>
      <AdminReport05PageContent />
    </UIXThemeProvider>
  );
}

const AdminReport05PageContent = memo(function AdminReport05PageContent() {
  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("AdminReport05Page: 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_insurance_report_${timestamp}.csv`;

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

      if (import.meta.env.DEV) {
        console.log("AdminReport05Page: Report downloaded successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminReport05Page: 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 Insurance Report"
      reportDescription="Generate a report of all facilitators' insurance information"
      reportBreadcrumbLabel="Facilitator Insurance"
      icon={ShieldCheckIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report will generate a CSV file containing current insurance information for all active facilitators. The report includes insurance policy details, expiration dates, and coverage types."
      recentDownloads={recentDownloads}
      reportId={5}
      reportType="Facilitator Insurance"
      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
          insurance 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 insurance status as of today's date.
            </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>
  );
});

AdminReport05PageContent.displayName = "AdminReport05PageContent";

export default AdminReport05Page;
