// File Path: monorepo/web/frontend/src/pages/Admin/Report/10To19/16Page.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,
  ChartPieIcon,
  GlobeAltIcon,
  UserIcon,
  UsersIcon,
} from "@heroicons/react/24/outline";

// User type options matching the old implementation
const USER_TYPE_OPTIONS = [
  { value: "", label: "Please select" },
  { value: 1, label: "Client" },
  { value: 2, label: "Facilitator" },
  { value: 3, label: "Staff" },
];

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

  // Form state
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");
  const [userType, setUserType] = 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 dates (last 30 days)
    const today = new Date();
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(today.getDate() - 30);

    setFromDate(thirtyDaysAgo.toISOString().split("T")[0]);
    setToDate(today.toISOString().split("T")[0]);

    // Load saved preferences
    const preferences = reportManager.getReportPreferences();
    if (preferences?.report16) {
      if (preferences.report16.fromDate) {
        setFromDate(preferences.report16.fromDate);
      }
      if (preferences.report16.toDate) {
        setToDate(preferences.report16.toDate);
      }
      if (preferences.report16.userType) {
        setUserType(preferences.report16.userType);
      }
    }
  }, []);

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

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

    // Validate from date
    if (!fromDate || fromDate === "") {
      newErrors.fromDate = "From date is required";
      hasErrors = true;
    }

    // Validate to date
    if (!toDate || toDate === "") {
      newErrors.toDate = "To date is required";
      hasErrors = true;
    }

    // Validate date range
    if (fromDate && toDate) {
      const from = new Date(fromDate);
      const to = new Date(toDate);

      if (from > to) {
        newErrors.toDate = "To date must be after from date";
        hasErrors = true;
      }
    }

    // Validate user type
    if (!userType || userType === "") {
      newErrors.userType = "User type is required";
      hasErrors = true;
    }

    return { errors: newErrors, hasErrors };
  };

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

    // 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 {
      // Convert dates to timestamps (matching old implementation)
      const fromDateObj = new Date(fromDate);
      const toDateObj = new Date(toDate);

      // Build parameters
      const params = {
        from_dt: fromDateObj.getTime(),
        to_dt: toDateObj.getTime(),
        user_type: parseInt(userType),
      };

      // Generate filename
      const timestamp = new Date().toISOString().split("T")[0];
      const userTypeName =
        USER_TYPE_OPTIONS.find(
          (opt) => opt.value === parseInt(userType),
        )?.label.toLowerCase() || "all";
      const filename = `how_users_find_us_long_${userTypeName}_${timestamp}.csv`;

      await reportManager.downloadReport(
        16, // Report ID for How Users Find Us (Long) 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({
        report16: {
          fromDate: fromDate,
          toDate: toDate,
          userType: userType,
        },
      });

      if (import.meta.env.DEV) {
        console.log("AdminReport16Page: Report downloaded successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminReport16Page: 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);
    }
  };

  // Handle date change
  const handleFromDateChange = (e) => {
    setFromDate(e.target.value);
    if (errors.fromDate) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors.fromDate;
        return newErrors;
      });
    }
  };

  const handleToDateChange = (e) => {
    setToDate(e.target.value);
    if (errors.toDate) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors.toDate;
        return newErrors;
      });
    }
  };

  // Get recent downloads from history
  const recentDownloads = reportManager.getReportHistory();

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

  return (
    <EntityReportDetail
      reportTitle="How Users Find Us (Long) Report"
      reportDescription="Detailed report on how users discovered our services"
      reportBreadcrumbLabel="How Users Find Us (Long)"
      icon={GlobeAltIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report generates a comprehensive CSV file showing how users of the selected type discovered your services during the specified date range. The report includes detailed referral sources, marketing channels, and user demographics based on their join date."
      recentDownloads={recentDownloads}
      reportId={16}
      reportType="How Users Find Us (Long)"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Date Range Section */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* From Date */}
          <div>
            <label
              htmlFor="fromDate"
              className="block text-sm font-medium text-gray-700 mb-2"
            >
              From Date
              <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="date"
                id="fromDate"
                name="fromDate"
                value={fromDate}
                onChange={handleFromDateChange}
                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.fromDate
                              ? "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
              />
            </div>
            <p className="mt-1 text-xs text-gray-500">
              Refers to user join date
            </p>
            {errors.fromDate && (
              <p className="mt-2 text-sm text-red-600 flex items-center">
                <ExclamationTriangleIcon className="h-4 w-4 mr-1" />
                {errors.fromDate}
              </p>
            )}
          </div>

          {/* To Date */}
          <div>
            <label
              htmlFor="toDate"
              className="block text-sm font-medium text-gray-700 mb-2"
            >
              To Date
              <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="date"
                id="toDate"
                name="toDate"
                value={toDate}
                onChange={handleToDateChange}
                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.toDate
                              ? "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
              />
            </div>
            <p className="mt-1 text-xs text-gray-500">
              Refers to user join date
            </p>
            {errors.toDate && (
              <p className="mt-2 text-sm text-red-600 flex items-center">
                <ExclamationTriangleIcon className="h-4 w-4 mr-1" />
                {errors.toDate}
              </p>
            )}
          </div>
        </div>

        {/* User Type Selection */}
        <div>
          <label
            htmlFor="userType"
            className="block text-sm font-medium text-gray-700 mb-2"
          >
            What type of user to filter by?
            <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">
              <UsersIcon className="h-5 w-5 text-gray-400" />
            </div>
            <select
              id="userType"
              name="userType"
              value={userType}
              onChange={(e) => {
                setUserType(e.target.value);
                if (errors.userType) {
                  setErrors((prev) => {
                    const newErrors = { ...prev };
                    delete newErrors.userType;
                    return newErrors;
                  });
                }
              }}
              className={`
                        w-full pl-10 pr-10 py-2.5 border rounded-lg
                        transition-all duration-200 appearance-none bg-white
                        focus:outline-none focus:ring-2 focus:ring-offset-1
                        ${
                          errors.userType
                            ? "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
            >
              {USER_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>
          <p className="mt-1 text-xs text-gray-500">
            Select the user category to include in the report
          </p>
          {errors.userType && (
            <p className="mt-2 text-sm text-red-600 flex items-center">
              <ExclamationTriangleIcon className="h-4 w-4 mr-1" />
              {errors.userType}
            </p>
          )}
        </div>

        {/* Report Preview */}
        {fromDate && toDate && userType && !Object.keys(errors).length && (
          <div className="bg-indigo-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">Date Range:</span>{" "}
                {new Date(fromDate).toLocaleDateString()} to{" "}
                {new Date(toDate).toLocaleDateString()}
              </p>
              <p>
                <span className="font-medium">User Type:</span>{" "}
                {USER_TYPE_OPTIONS.find(
                  (opt) => opt.value === parseInt(userType),
                )?.label || "All"}
              </p>
              <p>
                <span className="font-medium">Report Type:</span> Detailed
                referral source analysis
              </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 AdminReport16Page;
