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

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

function AdminReport09Page() {
  return (
    <UIXThemeProvider>
      <AdminReport09PageContent />
    </UIXThemeProvider>
  );
}

function AdminReport09PageContent() {
  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("AdminReport09Page: 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 = `client_addresses_report_${timestamp}.csv`;

      await reportManager.downloadReport(
        9, // Report ID for Client Addresses 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({
        lastClientAddressesReport: {
          lastDownloaded: new Date().toISOString(),
        },
      });

      if (import.meta.env.DEV) {
        console.log("AdminReport09Page: Report downloaded successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminReport09Page: 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="Client Addresses Report"
      reportDescription="Generate a comprehensive report of all client addresses and contact information"
      reportBreadcrumbLabel="Client Addresses"
      icon={MapPinIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report will generate a CSV file containing all client addresses and contact information. The report includes mailing addresses, phone numbers, email addresses, and geographic distribution data."
      recentDownloads={recentDownloads}
      reportId={9}
      reportType="Client Addresses"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      {/* Simple Download Section */}
      <div className="bg-blue-50 rounded-lg p-6 text-center">
        <MapPinIcon className="w-12 h-12 text-blue-600 mx-auto mb-4" />
        <h3 className="text-lg font-medium text-gray-900 mb-2">
          Generate and Download Report
        </h3>
        <p className="text-sm text-gray-600 mb-6">
          There are no fields to choose from. Simply click the button below to
          generate and download the complete client addresses report.
        </p>

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

      {/* Additional Information */}
      <div className="mt-6 p-4 bg-gray-50 rounded-lg">
        <div className={`text-sm ${getThemeClasses("text-color")}`}>
          <p className="font-medium mb-1">Quick Tip:</p>
          <p>
            This report automatically includes all active clients in your
            system. The data is current as of the moment you generate the
            report. You can import the CSV file into mapping software or mailing
            services.
          </p>
        </div>
      </div>
    </EntityReportDetail>
  );
}

export default AdminReport09Page;
