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

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

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

  // Form state
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");
  const [jobStatus, setJobStatus] = useState(0);

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

  // Load preferences and set default dates on mount
  useEffect(() => {
    // Set default dates (last 30 days)
    const today = new Date();
    const thirtyDaysAgo = new Date(today);
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

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

    // Load saved preferences
    const preferences = reportManager.getReportPreferences();
    if (preferences?.report10) {
      setJobStatus(preferences.report10.jobStatus || 0);
    }
  }, []);

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

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

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

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

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

      // Check for future dates
      const today = new Date();
      today.setHours(23, 59, 59, 999);

      if (to > today) {
        newErrors.toDate = "To date cannot be in the future";
        hasErrors = true;
      }
    }

    return { errors: newErrors, hasErrors };
  };

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

    // 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
      const fromDateObj = new Date(fromDate);
      const toDateObj = new Date(toDate);

      // Build parameters
      const params = {
        from_dt: fromDateObj.getTime(),
        to_dt: toDateObj.getTime(),
        state: parseInt(jobStatus) || 0,
      };

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

      await reportManager.downloadReport(
        10, // Report ID for Residential Jobs 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({
        report10: {
          jobStatus: jobStatus,
        },
      });

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

  // Calculate summary statistics from date range
  const getDateRangeSummary = () => {
    if (!fromDate || !toDate) return null;

    const from = new Date(fromDate);
    const to = new Date(toDate);
    const daysDiff = Math.floor((to - from) / (1000 * 60 * 60 * 24)) + 1;

    return {
      days: daysDiff,
      weeks: Math.floor(daysDiff / 7),
      months: Math.floor(daysDiff / 30),
    };
  };

  const dateRangeSummary = getDateRangeSummary();

  // Job status options
  const jobStatusOptions = [
    { value: 0, label: "All Statuses" },
    { value: 1, label: "New" },
    { value: 2, label: "In Progress" },
    { value: 3, label: "Completed" },
    { value: 4, label: "Cancelled" },
    { value: 5, label: "Pending" },
  ];

  return (
    <EntityReportDetail
      reportTitle="Residential Jobs Report"
      reportDescription="Generate a detailed report of residential work orders within a date range"
      reportBreadcrumbLabel="Residential Jobs"
      icon={HomeModernIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report will generate a CSV file containing all residential jobs within the specified date range. The dates refer to the assignment date of the work orders. The report includes customer details, job descriptions, assigned facilitators, and completion status."
      recentDownloads={recentDownloads}
      reportId={10}
      reportType="Residential Jobs"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Date Range Row */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* From Date Field */}
          <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={(e) => {
                  setFromDate(e.target.value);
                  if (errors.fromDate) {
                    setErrors((prev) => {
                      const newErrors = { ...prev };
                      delete newErrors.fromDate;
                      return newErrors;
                    });
                  }
                }}
                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>
            {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>
            )}
            <p className="mt-1 text-xs text-gray-500">
              Refers to assignment date
            </p>
          </div>

          {/* To Date Field */}
          <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={(e) => {
                  setToDate(e.target.value);
                  if (errors.toDate) {
                    setErrors((prev) => {
                      const newErrors = { ...prev };
                      delete newErrors.toDate;
                      return newErrors;
                    });
                  }
                }}
                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>
            {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>
            )}
            <p className="mt-1 text-xs text-gray-500">
              Refers to assignment date
            </p>
          </div>
        </div>

        {/* Job Status Filter */}
        <div>
          <label
            htmlFor="jobStatus"
            className="block text-sm font-medium text-gray-700 mb-2"
          >
            Job Status Filter
          </label>
          <div className="relative">
            <select
              id="jobStatus"
              name="jobStatus"
              value={jobStatus}
              onChange={(e) => setJobStatus(parseInt(e.target.value))}
              className="w-full px-4 py-2.5 pr-10 border border-gray-300 rounded-lg
                        transition-all duration-200 appearance-none bg-white
                        focus:outline-none focus:ring-2 focus:ring-offset-1
                        focus:border-blue-500 focus:ring-blue-500/20"
            >
              {jobStatusOptions.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">
            Filter by job status or select "All Statuses" to include everything
          </p>
        </div>

        {/* Date Range Summary */}
        {dateRangeSummary && (
          <div className="bg-green-50 rounded-lg p-4">
            <h4 className="text-sm font-medium text-gray-700 mb-2">
              Date Range Summary
            </h4>
            <div className="grid grid-cols-3 gap-4 text-center">
              <div>
                <p className="text-2xl font-bold text-gray-900">
                  {dateRangeSummary.days}
                </p>
                <p className="text-xs text-gray-500">Days</p>
              </div>
              <div>
                <p className="text-2xl font-bold text-gray-900">
                  {dateRangeSummary.weeks}
                </p>
                <p className="text-xs text-gray-500">Weeks</p>
              </div>
              <div>
                <p className="text-2xl font-bold text-gray-900">
                  {dateRangeSummary.months}
                </p>
                <p className="text-xs text-gray-500">Months</p>
              </div>
            </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 AdminReport10Page;
