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

import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router";
import { useReportManager } from "../../../../services/Services";
import {
  Button,
  EntityReportDetail,
  Loading,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  CalendarDaysIcon,
  CalendarIcon,
  ExclamationCircleIcon,
  ShieldCheckIcon,
  UserIcon,
} from "@heroicons/react/24/outline";

// Expiry date type options
const FACILITATOR_EXPIRY_DATE_TYPE_OPTIONS = [
  { value: 0, label: "Please select" },
  { value: 1, label: "Commercial Insurance Expiry Date" },
  { value: 2, label: "Police Check" },
];

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

  // Form state
  const [expiryDateType, setExpiryDateType] = useState(0);
  const [daysBeforeExpiry, setDaysBeforeExpiry] = useState("");

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

  // Load preferences on mount
  useEffect(() => {
    // Set default days
    setDaysBeforeExpiry("30");

    // Load saved preferences
    const preferences = reportManager.getReportPreferences();
    if (preferences?.report15) {
      setExpiryDateType(preferences.report15.expiryDateType || 0);
      setDaysBeforeExpiry(preferences.report15.daysBeforeExpiry || "30");
    }
  }, []);

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

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

    // Validate expiry date type
    if (!expiryDateType || expiryDateType <= 0) {
      newErrors.expiryDateType = "Please select an expiry date type";
      hasErrors = true;
    }

    // Validate days before expiry
    if (!daysBeforeExpiry || daysBeforeExpiry === "") {
      newErrors.daysBeforeExpiry = "Days before expiry is required";
      hasErrors = true;
    } else {
      const days = parseInt(daysBeforeExpiry);
      if (isNaN(days)) {
        newErrors.daysBeforeExpiry = "Please enter a valid number";
        hasErrors = true;
      } else if (days < 0) {
        newErrors.daysBeforeExpiry = "Days must be 0 or greater";
        hasErrors = true;
      } else if (days > 365) {
        newErrors.daysBeforeExpiry = "Days cannot exceed 365";
        hasErrors = true;
      }
    }

    return { errors: newErrors, hasErrors };
  };

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

    // 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 = {
        expiry_date_type: parseInt(expiryDateType),
        days_before_expiry: parseInt(daysBeforeExpiry),
      };

      // Generate filename
      const timestamp = new Date().toISOString().split("T")[0];
      const expiryTypeName =
        expiryDateType === 1 ? "insurance" : "police_check";
      const filename = `facilitator_expiry_${expiryTypeName}_${timestamp}.csv`;

      await reportManager.downloadReport(
        15, // Report ID for Facilitator Expiry Dates 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({
        report15: {
          expiryDateType: expiryDateType,
          daysBeforeExpiry: daysBeforeExpiry,
        },
      });

      if (import.meta.env.DEV) {
        console.log("AdminReport15Page: Report downloaded successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminReport15Page: 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 message="Loading report settings..." />;
  }

  return (
    <EntityReportDetail
      reportTitle="Facilitator Expiry Dates Report"
      reportDescription="Track upcoming expiry dates for facilitator documents and certifications"
      reportBreadcrumbLabel="Facilitator Expiry Dates"
      icon={CalendarDaysIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report will generate a CSV file containing all facilitators whose selected documents will expire within the specified number of days. Use this to proactively manage compliance and certification renewals for your facilitators."
      recentDownloads={recentDownloads}
      reportId={15}
      reportType="Facilitator Expiry Dates"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Expiry Date Type Selection */}
        <div>
          <label
            htmlFor="expiryDateType"
            className="block text-sm font-medium text-gray-700 mb-2"
          >
            What expiry date are you looking for?
            <span className="text-red-500 ml-1">*</span>
          </label>
          <div className="relative">
            <select
              id="expiryDateType"
              name="expiryDateType"
              value={expiryDateType}
              onChange={(e) => {
                setExpiryDateType(parseInt(e.target.value));
                if (errors.expiryDateType) {
                  setErrors((prev) => {
                    const newErrors = { ...prev };
                    delete newErrors.expiryDateType;
                    return newErrors;
                  });
                }
              }}
              className={`
                        w-full px-4 py-2.5 pr-10 border rounded-lg
                        transition-all duration-200 appearance-none bg-white
                        focus:outline-none focus:ring-2 focus:ring-offset-1
                        ${
                          errors.expiryDateType
                            ? "border-red-500 focus:border-red-500 focus:ring-red-500/20"
                            : "border-gray-300 focus:border-blue-500 focus:ring-blue-500/20"
                        }
                      `}
              required
            >
              {FACILITATOR_EXPIRY_DATE_TYPE_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
            <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2">
              <svg
                className="h-5 w-5 text-gray-400"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 20 20"
                fill="currentColor"
              >
                <path
                  fillRule="evenodd"
                  d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
                  clipRule="evenodd"
                />
              </svg>
            </div>
          </div>
          {errors.expiryDateType && (
            <p className="mt-2 text-sm text-red-600 flex items-center">
              <ExclamationTriangleIcon className="h-4 w-4 mr-1" />
              {errors.expiryDateType}
            </p>
          )}
        </div>

        {/* Days Before Expiry Input */}
        <div>
          <label
            htmlFor="daysBeforeExpiry"
            className="block text-sm font-medium text-gray-700 mb-2"
          >
            Days until expiry
            <span className="text-red-500 ml-1">*</span>
          </label>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <CalendarIcon className="h-5 w-5 text-gray-400" />
            </div>
            <input
              type="number"
              id="daysBeforeExpiry"
              name="daysBeforeExpiry"
              value={daysBeforeExpiry}
              onChange={(e) => {
                setDaysBeforeExpiry(e.target.value);
                if (errors.daysBeforeExpiry) {
                  setErrors((prev) => {
                    const newErrors = { ...prev };
                    delete newErrors.daysBeforeExpiry;
                    return newErrors;
                  });
                }
              }}
              min="0"
              max="365"
              className={`
                        w-full pl-10 pr-3 py-2.5
                        border rounded-lg
                        transition-all duration-200
                        focus:outline-none focus:ring-2 focus:ring-offset-1
                        ${
                          errors.daysBeforeExpiry
                            ? "border-red-500 focus:border-red-500 focus:ring-red-500/20"
                            : "border-gray-300 focus:border-blue-500 focus:ring-blue-500/20"
                        }
                      `}
              placeholder="e.g., 30"
              required
            />
          </div>
          <p className="mt-1 text-xs text-gray-500">
            Indicate how many days before the date will expire (0 to 365 days)
          </p>
          {errors.daysBeforeExpiry && (
            <p className="mt-2 text-sm text-red-600 flex items-center">
              <ExclamationTriangleIcon className="h-4 w-4 mr-1" />
              {errors.daysBeforeExpiry}
            </p>
          )}
        </div>

        {/* Report Preview */}
        {expiryDateType > 0 && daysBeforeExpiry && !errors.daysBeforeExpiry && (
          <div className="bg-orange-50 rounded-lg p-4">
            <h4 className="text-sm font-medium text-gray-700 mb-2">
              Report Preview
            </h4>
            <div className="text-sm text-gray-600 space-y-1">
              <p>
                <span className="font-medium">Document Type:</span>{" "}
                {FACILITATOR_EXPIRY_DATE_TYPE_OPTIONS[expiryDateType]?.label}
              </p>
              <p>
                <span className="font-medium">Time Frame:</span> Documents
                expiring within {daysBeforeExpiry} day
                {daysBeforeExpiry !== "1" ? "s" : ""}
              </p>
              <p>
                <span className="font-medium">Report Type:</span> Facilitator
                compliance tracking
              </p>
            </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")}
          >
            Back to Reports
          </Button>
          <Button
            type="submit"
            variant="primary"
            disabled={isSubmitting}
            loading={isSubmitting}
          >
            {isSubmitting ? "Generating..." : "Download Report"}
          </Button>
        </div>
      </form>
    </EntityReportDetail>
  );
}

export default AdminReport15Page;
