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

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

const RentalCancellationModal: React.FC<RentalCancellationModalProps> = ({
  show,
  onHide,
  rental,
  onCancellationComplete,
}) => {
  const [refundPreview, setRefundPreview] = useState<RefundPreview | null>(
    null
  );
  const [loading, setLoading] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [reason, setReason] = useState("");

  useEffect(() => {
    if (show && rental) {
      loadRefundPreview();
    }
  }, [show, rental]);

  const loadRefundPreview = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await rentalAPI.getRefundPreview(rental.id);
      setRefundPreview(response.data);
    } catch (error: any) {
      setError(
        error.response?.data?.error || "Failed to calculate refund preview"
      );
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = async () => {
    if (!refundPreview) return;

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

      const response = await rentalAPI.cancelRental(rental.id, reason.trim());
      onCancellationComplete(response.data.rental);
      onHide();
    } catch (error: any) {
      setError(error.response?.data?.error || "Failed to cancel rental");
    } finally {
      setProcessing(false);
    }
  };

  const formatCurrency = (amount: number | string | undefined) => {
    const numAmount = Number(amount) || 0;
    return `$${numAmount.toFixed(2)}`;
  };

  const getRefundColor = (percentage: number) => {
    if (percentage === 0) return "danger";
    if (percentage === 0.5) return "warning";
    return "success";
  };

  const handleBackdropClick = useCallback(
    (e: React.MouseEvent) => {
      if (e.target === e.currentTarget) {
        onHide();
      }
    },
    [onHide]
  );

  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onHide();
      }
    },
    [onHide]
  );

  useEffect(() => {
    if (show) {
      document.addEventListener("keydown", handleKeyDown);
      document.body.style.overflow = "hidden";
    } else {
      document.removeEventListener("keydown", handleKeyDown);
      document.body.style.overflow = "unset";
    }

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

  if (!show) return null;

  return (
    <div
      className="modal d-block"
      style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
      onClick={handleBackdropClick}
    >
      <div className="modal-dialog modal-lg modal-dialog-centered">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">Cancel Rental</h5>
            <button
              type="button"
              className="btn-close"
              onClick={onHide}
              aria-label="Close"
            ></button>
          </div>
          <div className="modal-body">
            {loading && (
              <div className="text-center py-4">
                <div className="spinner-border me-2" role="status">
                  <span className="visually-hidden">Loading...</span>
                </div>
                Calculating refund...
              </div>
            )}

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

            {refundPreview && !loading && (
              <>
                <div className="mb-4">
                  <h5>Rental Details</h5>
                  <div className="bg-light p-3 rounded">
                    <p>
                      <strong>Item:</strong> {rental.item?.name}
                    </p>
                    <p>
                      <strong>Start:</strong>{" "}
                      {new Date(rental.startDateTime).toLocaleString()}
                    </p>
                    <p>
                      <strong>End:</strong>{" "}
                      {new Date(rental.endDateTime).toLocaleString()}
                    </p>
                    <p>
                      <strong>Total Amount:</strong>{" "}
                      {formatCurrency(rental.totalAmount)}
                    </p>
                  </div>
                </div>

                <div className="mb-4">
                  <h5>Refund Information</h5>
                  <div
                    className={`alert alert-${getRefundColor(
                      refundPreview.refundPercentage
                    )}`}
                  >
                    <div className="d-flex justify-content-between align-items-center">
                      <div>
                        <strong>Refund Amount:</strong>{" "}
                        {formatCurrency(refundPreview.refundAmount)}
                      </div>
                      <div>
                        <strong>
                          {Math.round(refundPreview.refundPercentage * 100)}%
                        </strong>
                      </div>
                    </div>
                    <hr />
                    <small>{refundPreview.reason}</small>
                  </div>
                </div>

                <form>
                  <div className="mb-3">
                    <label className="form-label">
                      Cancellation Reason (Optional)
                    </label>
                    <textarea
                      className="form-control"
                      rows={3}
                      value={reason}
                      onChange={(e) => setReason(e.target.value)}
                      placeholder="Please provide a reason for cancellation..."
                      maxLength={500}
                    />
                    <div className="form-text text-muted">
                      {reason.length}/500 characters
                    </div>
                  </div>
                </form>
              </>
            )}
          </div>
          <div className="modal-footer">
            <button
              type="button"
              className="btn btn-secondary"
              onClick={onHide}
              disabled={processing}
            >
              Keep Rental
            </button>
            {refundPreview && (
              <button
                type="button"
                className="btn btn-danger"
                onClick={handleCancel}
                disabled={processing || loading}
              >
                {processing ? (
                  <>
                    <div
                      className="spinner-border spinner-border-sm me-2"
                      role="status"
                    >
                      <span className="visually-hidden">Loading...</span>
                    </div>
                    Processing...
                  </>
                ) : (
                  `Cancel with ${
                    refundPreview.refundAmount > 0
                      ? `Refund ${formatCurrency(refundPreview.refundAmount)}`
                      : "No Refund"
                  }`
                )}
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default RentalCancellationModal;
