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

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

function AdminReport08Page() {
  return (
    <UIXThemeProvider>
      <AdminReport08PageContent />
    </UIXThemeProvider>
  );
}

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

  // Form state
  const [facilitatorId, setFacilitatorId] = useState("");

  // UI state
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);

  // Load saved preferences on mount
  useEffect(() => {
    const preferences = reportManager.getReportPreferences();
    if (preferences?.report08) {
      setFacilitatorId(preferences.report08.lastFacilitatorId || "");
    }
  }, []);

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

  // Validate form
  const validateForm = () => {
    const newErrors = {};
    let hasErrors = false;

    // Validate facilitator selection
    if (!facilitatorId || facilitatorId === "" || facilitatorId === "0") {
      newErrors.facilitatorId = "Please select a facilitator";
      hasErrors = true;
    }

    return { errors: newErrors, hasErrors };
  };

  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (import.meta.env.DEV) {
      console.log(
        "AdminReport08Page: Submitting report for facilitator:",
        facilitatorId,
      );
    }

    // Validate
    const validation = validateForm();
    if (validation.hasErrors) {
      setErrors(validation.errors);
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }

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

    try {
      // Build parameters
      const params = {
        facilitator_id: facilitatorId,
      };

      // Generate filename
      const timestamp = new Date().toISOString().split("T")[0];
      const filename = `facilitator_skill_sets_report_${facilitatorId}_${timestamp}.csv`;

      await reportManager.downloadReport(
        8, // Report ID for Facilitator Skill Sets 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({
        report08: {
          lastFacilitatorId: facilitatorId,
        },
      });

      if (import.meta.env.DEV) {
        console.log("AdminReport08Page: Report downloaded successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminReport08Page: 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 Skill Sets Report"
      reportDescription="Generate a detailed report of skill sets for a specific facilitator"
      reportBreadcrumbLabel="Facilitator Skill Sets"
      icon={AcademicCapIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report will generate a CSV file containing all skill sets and certifications for the selected facilitator. The report includes skill categories, proficiency levels, certification dates, and expiration information."
      recentDownloads={recentDownloads}
      reportId={8}
      reportType="Facilitator Skill Sets"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Facilitator Selection */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Select Facilitator
            <span className="text-red-500 ml-1">*</span>
          </label>
          <FacilitatorSelect
            value={facilitatorId}
            onChange={(value) => {
              setFacilitatorId(value);
              // Clear error when user selects a facilitator
              if (errors.facilitatorId) {
                setErrors((prev) => {
                  const newErrors = { ...prev };
                  delete newErrors.facilitatorId;
                  return newErrors;
                });
              }
            }}
            error={errors.facilitatorId}
            required={true}
            placeholder="Search and select a facilitator..."
            helperText="Start typing to search for a facilitator by name or ID"
            onUnauthorized={onUnauthorized}
          />
        </div>

        {/* 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 || !facilitatorId}
            loading={isSubmitting}
            loadingText="Generating..."
          >
            Download Report
          </Button>
        </div>
      </form>
    </EntityReportDetail>
  );
});

AdminReport08PageContent.displayName = "AdminReport08PageContent";

export default AdminReport08Page;
