// File Path: monorepo/web/frontend/src/pages/Admin/Report/20To29/21Page.jsx

import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router";
import { useReportManager } from "../../../../services/Services";
import { Card, Button, Loading } from "../../../../components/UI";
import { EntityReportDetail } from "../../../../components/UIX";
import {
  ArrowLeftIcon,
  EnvelopeIcon,
  AtSymbolIcon,
  ChartPieIcon,
  UserGroupIcon,
  DocumentTextIcon,
  BellAlertIcon,
  MegaphoneIcon,
} from "@heroicons/react/24/outline";

function AdminReport21Page() {
  const navigate = useNavigate();
  const reportManager = useReportManager();

  // UI state
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isLoading, setIsLoading] = 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("AdminReport21Page: 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 = `marketing_emails_report_${timestamp}.csv`;

      await reportManager.downloadReport(
        21, // Report ID for Marketing Emails Report
        params,
        filename,
        onUnauthorized,
      );

      // Show success message
      setShowSuccess(true);

      // Hide success message after 5 seconds
      setTimeout(() => {
        setShowSuccess(false);
      }, 5000);

      // Save to history (no preferences needed for this report)
      if (import.meta.env.DEV) {
        console.log("AdminReport21Page: Report downloaded successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminReport21Page: 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();

  if (isLoading) {
    return <Loading fullScreen text="Loading report..." />;
  }

  return (
    <EntityReportDetail
      reportTitle="Marketing Emails Report"
      reportDescription="Export all users who have opted in to receive marketing emails"
      reportBreadcrumbLabel="Marketing Emails Report"
      icon={EnvelopeIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report generates a CSV file containing all users who have opted in to receive marketing emails. The export includes email addresses, names, subscription preferences, and signup dates."
      recentDownloads={recentDownloads}
      reportId={21}
      reportType="Marketing Emails Report"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      <div className="bg-gray-50 rounded-lg p-6 text-center mb-6">
        <MegaphoneIcon className="mx-auto h-12 w-12 text-gray-400 mb-4" />
        <h3 className="text-lg font-medium text-gray-900 mb-2">
          Ready to Export
        </h3>
        <p className="text-sm text-gray-600 mb-4">
          There are no parameters to configure for this report. Simply click the
          download button below to generate and download the complete marketing
          email list.
        </p>
        <div className="bg-white rounded-lg p-4 border border-gray-200">
          <div className="text-sm text-gray-600 space-y-1">
            <p>
              <span className="font-medium">Report Type:</span> Marketing email
              list
            </p>
            <p>
              <span className="font-medium">Format:</span> CSV (Excel
              compatible)
            </p>
            <p>
              <span className="font-medium">Content:</span> All opted-in users
            </p>
          </div>
        </div>
      </div>

      {/* Form Actions */}
      <div className="flex items-center justify-between pt-6 border-t border-gray-200">
        <Button
          type="button"
          variant="outline"
          onClick={() => navigate("/admin/reports")}
          icon={ArrowLeftIcon}
        >
          Back to Reports
        </Button>
        <Button
          type="button"
          variant="primary"
          disabled={isSubmitting}
          loading={isSubmitting}
          onClick={handleSubmit}
          icon={DocumentArrowDownIcon}
        >
          {isSubmitting ? "Generating..." : "Download Report"}
        </Button>
      </div>
    </EntityReportDetail>
  );
}

export default AdminReport21Page;
