import React, { useState, useEffect } from "react";
import { rentalAPI } from "../services/api";
import { Rental } from "../types";

interface DeclineRentalModalProps {
  show: boolean;
  onHide: () => void;
  rental: Rental;
  onDeclineComplete: (updatedRental: Rental) => void;
}

const DeclineRentalModal: React.FC<DeclineRentalModalProps> = ({
  show,
  onHide,
  rental,
  onDeclineComplete,
}) => {
  const [processing, setProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [reason, setReason] = useState("");
  const [success, setSuccess] = useState(false);
  const [updatedRental, setUpdatedRental] = useState<Rental | null>(null);

  const handleDecline = async () => {
    if (!reason.trim()) {
      setError("Please provide a reason for declining this request");
      return;
    }

    try {
      setProcessing(true);
      setError(null);

      const response = await rentalAPI.declineRental(rental.id, reason.trim());

      // Store updated rental data for later callback
      setUpdatedRental(response.data);

      // Show success confirmation
      setSuccess(true);
    } catch (error: any) {
      setError(
        error.response?.data?.error || "Failed to decline rental request"
      );
    } finally {
      setProcessing(false);
    }
  };

  const handleClose = () => {
    // Call parent callback with updated rental data if we have it
    if (updatedRental) {
      onDeclineComplete(updatedRental);

      // Notify Navbar to update pending count
      window.dispatchEvent(new CustomEvent("rentalStatusChanged"));
    }

    // Reset all states when closing
    setProcessing(false);
    setError(null);
    setReason("");
    setSuccess(false);
    setUpdatedRental(null);
    onHide();
  };

  useEffect(() => {
    if (show) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "unset";
    }

    return () => {
      document.body.style.overflow = "unset";
    };
  }, [show]);

  if (!show) return null;

  return (
    <div
      className="modal d-block"
      style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
    >
      <div className="modal-dialog modal-dialog-centered">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">
              {success ? "Request Declined" : "Decline Rental Request"}
            </h5>
            <button
              type="button"
              className="btn-close"
              onClick={handleClose}
              disabled={processing}
              aria-label="Close"
            ></button>
          </div>
          <div className="modal-body">
            {success ? (
              <div className="text-center py-4">
                <div className="mb-4">
                  <i
                    className="bi bi-check-circle-fill text-success"
                    style={{ fontSize: "4rem" }}
                  ></i>
                </div>
                <h3 className="text-success mb-3">Request Declined</h3>
                <div className="alert alert-info">
                  <p className="mb-0">
                    The renter has been notified that their request was
                    declined.
                  </p>
                </div>
              </div>
            ) : (
              <>
                <div className="mb-4">
                  <h6>Rental Details</h6>
                  <div className="bg-light p-3 rounded">
                    <p className="mb-2">
                      <strong>Item:</strong> {rental.item?.name}
                    </p>
                    <p className="mb-2">
                      <strong>Renter:</strong> {rental.renter?.firstName}{" "}
                      {rental.renter?.lastName}
                    </p>
                    <p className="mb-2">
                      <strong>Start:</strong>{" "}
                      {new Date(rental.startDateTime).toLocaleString()}
                    </p>
                    <p className="mb-0">
                      <strong>End:</strong>{" "}
                      {new Date(rental.endDateTime).toLocaleString()}
                    </p>
                  </div>
                </div>

                {error && (
                  <div className="alert alert-danger mb-3" role="alert">
                    {error}
                  </div>
                )}

                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    handleDecline();
                  }}
                >
                  <div className="mb-3">
                    <label className="form-label">
                      Reason for Declining{" "}
                      <span className="text-danger">*</span>
                    </label>
                    <textarea
                      className="form-control"
                      rows={4}
                      value={reason}
                      onChange={(e) => {
                        setReason(e.target.value);
                        setError(null);
                      }}
                      placeholder="Please explain why you're unable to accept this rental request..."
                      maxLength={500}
                      required
                      disabled={processing}
                    />
                    <div className="form-text text-muted">
                      {reason.length}/500 characters (Required)
                    </div>
                  </div>

                  <div className="alert alert-warning">
                    <i className="bi bi-exclamation-triangle-fill me-2"></i>
                    <strong>Note:</strong> The renter will see your reason for
                    declining. No payment has been processed for this request.
                  </div>
                </form>
              </>
            )}
          </div>
          <div className="modal-footer">
            {success ? (
              <button
                type="button"
                className="btn btn-primary"
                onClick={handleClose}
              >
                Done
              </button>
            ) : (
              <>
                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={handleClose}
                  disabled={processing}
                >
                  Cancel
                </button>
                <button
                  type="button"
                  className="btn btn-danger"
                  onClick={handleDecline}
                  disabled={processing || !reason.trim()}
                >
                  {processing ? (
                    <>
                      <div
                        className="spinner-border spinner-border-sm me-2"
                        role="status"
                      >
                        <span className="visually-hidden">Loading...</span>
                      </div>
                      Declining...
                    </>
                  ) : (
                    "Submit"
                  )}
                </button>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default DeclineRentalModal;
