// File Path: monorepo/web/frontend/src/pages/Admin/Report/20To29/20Page.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 {
  ExclamationTriangleIcon,
  ArrowLeftIcon,
  CreditCardIcon,
  CalendarIcon,
  BanknotesIcon,
  DocumentTextIcon,
  CurrencyDollarIcon,
  ReceiptPercentIcon,
  ChartPieIcon,
} from "@heroicons/react/24/outline";

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

  // Form state
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = 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?.report20) {
      if (preferences.report20.fromDate) {
        setFromDate(preferences.report20.fromDate);
      }
      if (preferences.report20.toDate) {
        setToDate(preferences.report20.toDate);
      }
    }
  }, []);

  // 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;
      }
    }

    return { errors: newErrors, hasErrors };
  };

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

    // 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(),
      };

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

      await reportManager.downloadReport(
        20, // Report ID for Payments 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({
        report20: {
          fromDate: fromDate,
          toDate: toDate,
        },
      });

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

  // Calculate date range info
  const getDateRangeInfo = () => {
    if (!fromDate || !toDate) return null;

    const from = new Date(fromDate);
    const to = new Date(toDate);
    const diffTime = Math.abs(to - from);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    return diffDays;
  };

  const dateRangeDays = getDateRangeInfo();

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

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

  return (
    <EntityReportDetail
      reportTitle="Payments Report"
      reportDescription="Generate a comprehensive report of all payments received"
      reportBreadcrumbLabel="Payments Report"
      icon={CreditCardIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report generates a detailed CSV file containing all payment transactions within the specified date range. It includes invoice details, payment amounts, service fees, customer information, and payment status."
      recentDownloads={recentDownloads}
      reportId={20}
      reportType="Payments Report"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      <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 the invoice service fee payment 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 the invoice service fee payment 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>

        {/* Report Preview */}
        {fromDate && toDate && !Object.keys(errors).length && (
          <div className="bg-green-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>
              {dateRangeDays !== null && (
                <p>
                  <span className="font-medium">Period:</span> {dateRangeDays}{" "}
                  day{dateRangeDays !== 1 ? "s" : ""}
                </p>
              )}
              <p>
                <span className="font-medium">Report Type:</span> Financial
                payment transactions
              </p>
              <p>
                <span className="font-medium">Format:</span> CSV with detailed
                payment data
              </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")}
            icon={ArrowLeftIcon}
          >
            Back to Reports
          </Button>
          <Button
            type="submit"
            variant="primary"
            disabled={isSubmitting}
            loading={isSubmitting}
            icon={DocumentArrowDownIcon}
          >
            {isSubmitting ? "Generating..." : "Download Report"}
          </Button>
        </div>
      </form>
    </EntityReportDetail>
  );
}

export default AdminReport20Page;
