// File Path: monorepo/web/frontend/src/pages/Admin/Report/10To19/12Page.jsx

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

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

  // 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 report download
  const handleDownload = async () => {
    if (import.meta.env.DEV) {
      console.log("AdminReport12Page: Downloading Skill Sets Report");
    }

    // Clear any previous errors
    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 = `skill_sets_report_${timestamp}.csv`;

      await reportManager.downloadReport(
        12, // Report ID for Skill Sets Report
        params,
        filename,
        onUnauthorized,
      );

      // Show success message
      setShowSuccess(true);

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

      if (import.meta.env.DEV) {
        console.log("AdminReport12Page: Report downloaded successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminReport12Page: 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="Skill Sets Report"
      reportDescription="Generate a complete list of all skill sets in the system"
      reportBreadcrumbLabel="Skill Sets"
      icon={WrenchScrewdriverIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report will generate a CSV file containing all skill sets currently configured in the system. No filters or parameters are needed - simply click the download button to generate the complete list."
      recentDownloads={recentDownloads}
      reportId={12}
      reportType="Skill Sets"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      {/* Simple Download Section */}
      <div className="bg-gray-50 rounded-lg p-6 text-center">
        <WrenchScrewdriverIcon className="w-12 h-12 text-purple-600 mx-auto mb-4" />
        <h3 className="text-lg font-medium text-gray-900 mb-2">
          Ready to Generate
        </h3>
        <p className="text-sm text-gray-600 mb-6">
          There are no fields to configure. Simply click the download button
          below to generate and download the complete skill sets report.
        </p>

        {/* Download Statistics */}
        <div className="grid grid-cols-3 gap-4 mb-6">
          <div className="bg-white rounded-lg p-3">
            <p className="text-2xl font-bold text-purple-600">CSV</p>
            <p className="text-xs text-gray-500">Format</p>
          </div>
          <div className="bg-white rounded-lg p-3">
            <p className="text-2xl font-bold text-purple-600">All</p>
            <p className="text-xs text-gray-500">Records</p>
          </div>
          <div className="bg-white rounded-lg p-3">
            <p className="text-2xl font-bold text-purple-600">
              {recentDownloads.length}
            </p>
            <p className="text-xs text-gray-500">Recent</p>
          </div>
        </div>

        <Button
          type="button"
          variant="primary"
          size="lg"
          disabled={isSubmitting}
          loading={isSubmitting}
          icon={DocumentArrowDownIcon}
          onClick={handleDownload}
          className="w-full sm:w-auto"
        >
          {isSubmitting ? "Generating Report..." : "Download Report"}
        </Button>
      </div>

      {/* Navigation */}
      <div className="flex items-center justify-between pt-6 border-t border-gray-200 mt-6">
        <Button
          type="button"
          variant="outline"
          onClick={() => navigate("/admin/reports")}
        >
          Back to Reports
        </Button>
      </div>
    </EntityReportDetail>
  );
}

export default AdminReport12Page;
