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

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

function AdminReport07Page() {
  return (
    <UIXThemeProvider>
      <AdminReport07PageContent />
    </UIXThemeProvider>
  );
}

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

  // Facilitator status filter options
  const facilitatorStatusOptions = [
    { value: "0", label: "All Facilitators" },
    { value: "1", label: "Active Facilitators" },
    { value: "2", label: "Archived Facilitators" },
  ];

  // State
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);
  const [facilitatorStatus, setFacilitatorStatus] = useState("0");

  // Load saved preferences on mount
  useEffect(() => {
    const preferences = reportManager.getReportPreferences();
    if (preferences?.report07) {
      setFacilitatorStatus(
        String(preferences.report07.facilitatorStatus || 0),
      );
    }
  }, []);

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

  // Submit handler
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (import.meta.env.DEV) {
      console.log("Report07Page: Submitting report");
    }

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

    try {
      // Build parameters
      const params = {
        state: parseInt(facilitatorStatus) || 0,
      };

      // Download report
      const reportId = 7;
      const timestamp = new Date().toISOString().split("T")[0];
      const filename = `facilitator_birthdays_report_${timestamp}.csv`;

      if (import.meta.env.DEV) {
        console.log("Report07Page: Downloading report with params:", params);
      }

      await reportManager.downloadReport(
        reportId,
        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({
        report07: {
          facilitatorStatus: parseInt(facilitatorStatus),
        },
      });

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

      // Handle errors
      if (error && typeof error === "object") {
        setErrors(error);
      } else {
        setErrors({
          general: "Failed to download report. Please try again.",
        });
      }

      // Scroll to top to show errors
      window.scrollTo({ top: 0, behavior: "smooth" });
    } finally {
      setIsSubmitting(false);
    }
  };

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

  return (
    <EntityReportDetail
      reportTitle="Facilitator Birthdays Report"
      reportDescription="Generate a report of all facilitators' birthdays for celebration planning"
      reportBreadcrumbLabel="Facilitator Birthdays"
      icon={CakeIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report will generate a CSV file containing birthday information for facilitators. Use this report to plan celebrations, send birthday cards, or recognize your team members on their special day. The report includes birth dates sorted by month and day."
      recentDownloads={recentDownloads}
      reportId={7}
      reportType="Facilitator Birthdays"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Facilitator Status Filter */}
        <Select
          label="Facilitator Status Filter"
          value={facilitatorStatus}
          onChange={(value) => setFacilitatorStatus(value)}
          options={facilitatorStatusOptions}
          error={errors.facilitatorStatus}
          helperText='Filter the report by facilitator status. Select "All Facilitators" to include everyone.'
        />

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

AdminReport07PageContent.displayName = "AdminReport07PageContent";

export default AdminReport07Page;
