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

import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router";
import { useReportManager } from "../../../../services/Services";
import { TagsMultiSelect } from "../../../../components/business/selects";
import { Card, Button, Loading, Select } from "../../../../components/UI";
import { EntityReportDetail } from "../../../../components/UIX";
import {
  CalendarDaysIcon,
  ExclamationTriangleIcon,
  ArrowLeftIcon,
  TagIcon,
  CalendarIcon,
  BriefcaseIcon,
  ClipboardDocumentCheckIcon,
  ChartPieIcon,
} from "@heroicons/react/24/outline";

// Job status filter options matching the old implementation
const JOB_STATUS_OPTIONS = [
  { value: 0, label: "All" },
  { value: 1, label: "New" },
  { value: 2, label: "Declined" },
  { value: 3, label: "Pending" },
  { value: 4, label: "Cancelled" },
  { value: 5, label: "Ongoing" },
  { value: 6, label: "In progress" },
  { value: 7, label: "Completed but unpaid" },
  { value: 8, label: "Completed and paid" },
  { value: 9, label: "Archived" },
];

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

  // Form state
  const [tags, setTags] = useState([]);
  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 [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?.report19) {
      if (preferences.report19.tags) {
        setTags(preferences.report19.tags);
      }
      if (preferences.report19.fromDate) {
        setFromDate(preferences.report19.fromDate);
      }
      if (preferences.report19.toDate) {
        setToDate(preferences.report19.toDate);
      }
      if (preferences.report19.jobStatus !== undefined) {
        setJobStatus(preferences.report19.jobStatus);
      }
    }
  }, []);

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

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

    // Validate tags
    if (!tags || tags.length === 0) {
      newErrors.tags = "At least one tag is required";
      hasErrors = true;
    }

    // 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("AdminReport19Page: Submitting report", {
        tags,
        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 (matching old implementation)
      const fromDateObj = new Date(fromDate);
      const toDateObj = new Date(toDate);

      // Build parameters with tag_ids as comma-separated string
      const params = {
        from_dt: fromDateObj.getTime(),
        to_dt: toDateObj.getTime(),
        state: parseInt(jobStatus),
        tag_ids: tags.join(","), // Convert array to comma-separated string
      };

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

      await reportManager.downloadReport(
        19, // Report ID for Job Tags by Assignment 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({
        report19: {
          tags: tags,
          fromDate: fromDate,
          toDate: toDate,
          jobStatus: jobStatus,
        },
      });

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

  // Handle tags change
  const handleTagsChange = (newTags) => {
    setTags(newTags);
    if (errors.tags) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors.tags;
        return newErrors;
      });
    }
  };

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

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

  return (
    <EntityReportDetail
      reportTitle="Job Tags by Assignment Dates Report"
      reportDescription="Generate a report of work orders filtered by tags and assignment dates"
      reportBreadcrumbLabel="Job Tags by Assignment Dates"
      icon={TagIcon}
      showSuccess={showSuccess}
      errors={errors}
      infoMessage="This report generates a CSV file containing work orders that match the selected tags and fall within the specified assignment date range. Perfect for tracking work by category and time period."
      recentDownloads={recentDownloads}
      reportId={19}
      reportType="Job Tags by Assignment Dates"
      onDismissSuccess={() => setShowSuccess(false)}
      onDismissErrors={() => setErrors({})}
    >
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Tags Selection */}
        <div>
          <TagsMultiSelect
            value={tags}
            onChange={handleTagsChange}
            error={errors.tags}
            required={true}
            label="Tags"
            placeholder="Select tags to filter by..."
            helperText="Select one or more tags to include in the report"
            onUnauthorized={onUnauthorized}
          />
        </div>

        {/* 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 assignment 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 assignment 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>

        {/* Job Status Selection */}
        <div>
          <Select
            label="Job Status"
            value={jobStatus}
            onChange={(e) => setJobStatus(parseInt(e.target.value))}
            options={JOB_STATUS_OPTIONS}
            error={errors.jobStatus}
            helperText="Filter by work order status"
          />
        </div>

        {/* Report Preview */}
        {tags.length > 0 &&
          fromDate &&
          toDate &&
          !Object.keys(errors).length && (
            <div className="bg-purple-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">Tags:</span> {tags.length} tag
                  {tags.length !== 1 ? "s" : ""} selected
                </p>
                <p>
                  <span className="font-medium">Date Range:</span>{" "}
                  {new Date(fromDate).toLocaleDateString()} to{" "}
                  {new Date(toDate).toLocaleDateString()}
                </p>
                <p>
                  <span className="font-medium">Job Status:</span>{" "}
                  {JOB_STATUS_OPTIONS.find((opt) => opt.value === jobStatus)
                    ?.label || "All"}
                </p>
                <p>
                  <span className="font-medium">Report Type:</span> Detailed
                  work order analysis
                </p>
                <p>
                  <span className="font-medium">Format:</span> CSV with full
                  work order details
                </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 AdminReport19Page;
