import React, { useState, useEffect } 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("");
  const [success, setSuccess] = useState(false);
  const [processedRefund, setProcessedRefund] = useState<{
    amount: number;
    refundId?: string;
  } | null>(null);
  const [updatedRental, setUpdatedRental] = useState<Rental | null>(null);

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

  const loadRefundPreview = async () => {
    try {
      setLoading(true);
      setError(null);

      // Check if rental status allows cancellation before making API call
      if (rental.status !== "pending" && rental.status !== "confirmed") {
        let errorMessage = "This rental cannot be cancelled";
        if (rental.status === "active") {
          errorMessage = "Cannot cancel rental - the rental period has already started";
        } else if (rental.status === "completed") {
          errorMessage = "Cannot cancel rental - the rental has already been completed";
        } else if (rental.status === "cancelled") {
          errorMessage = "This rental has already been cancelled";
        }
        setError(errorMessage);
        return;
      }

      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;

    // Validate reason is provided
    const trimmedReason = reason.trim();
    if (!trimmedReason) {
      setError("Please provide a cancellation reason");
      return;
    }

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

      const response = await rentalAPI.cancelRental(rental.id, trimmedReason);
      
      // Store refund details for confirmation screen
      setProcessedRefund({
        amount: refundPreview.refundAmount,
        refundId: response.data.rental.stripeRefundId
      });
      
      // Store updated rental data for later callback
      setUpdatedRental(response.data.rental);
      
      // Show success confirmation instead of closing immediately
      setSuccess(true);
      // Don't call onCancellationComplete here - wait until user clicks "Done"
    } catch (error: any) {
      setError(error.response?.data?.error || "Failed to cancel rental");
    } finally {
      setProcessing(false);
    }
  };

  const handleClose = () => {
    // Call parent callback with updated rental data if we have it
    if (updatedRental) {
      onCancellationComplete(updatedRental);
    }
    
    // Reset all states when closing
    setRefundPreview(null);
    setLoading(false);
    setProcessing(false);
    setError(null);
    setReason("");
    setSuccess(false);
    setProcessedRefund(null);
    setUpdatedRental(null);
    onHide();
  };

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

  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-lg modal-dialog-centered">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">
              {success
                ? (rental.totalAmount > 0 ? "Refund Confirmation" : "Cancellation Confirmation")
                : "Cancel Rental"
              }
            </h5>
            <button
              type="button"
              className="btn-close"
              onClick={handleClose}
              aria-label="Close"
            ></button>
          </div>
          <div className="modal-body">
            {success && processedRefund ? (
              <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">
                  {rental.totalAmount > 0 ? 'Refund Processed Successfully!' : 'Rental Cancelled Successfully!'}
                </h3>
                {rental.totalAmount > 0 && (
                  <div className="alert alert-success mb-4">
                    <h5 className="mb-3">
                      <strong>{formatCurrency(processedRefund.amount)}</strong> has been refunded
                    </h5>
                    <div className="small text-muted">
                      <p className="mb-2">
                        <i className="bi bi-clock me-2"></i>
                        Your refund will appear in your payment method within <strong>3-5 business days</strong>
                      </p>
                      <p className="mb-0">
                        <i className="bi bi-credit-card me-2"></i>
                        Refund will be processed to your original payment method
                      </p>
                    </div>
                  </div>
                )}
                <p className="text-muted mb-4">
                  Thank you for using our platform. We hope you'll rent with us again soon!
                </p>
              </div>
            ) : (
              <>
                {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>

                {rental.totalAmount > 0 && (
                  <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 <span className="text-danger">*</span>
                    </label>
                    <textarea
                      className="form-control"
                      rows={3}
                      value={reason}
                      onChange={(e) => setReason(e.target.value)}
                      placeholder="Please provide a reason for cancellation..."
                      maxLength={500}
                      required
                    />
                    <div className="form-text text-muted">
                      {reason.length}/500 characters
                    </div>
                  </div>
                </form>
              </>
            )}
            </>
            )}
          </div>
          <div className="modal-footer">
            {success ? (
              <button
                type="button"
                className="btn btn-primary btn-lg"
                onClick={handleClose}
              >
                Done
              </button>
            ) : (
              <>
                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={handleClose}
                  disabled={processing}
                >
                  Keep Rental
                </button>
                {refundPreview && (
                  <button
                    type="button"
                    className="btn btn-danger"
                    onClick={handleCancel}
                    disabled={processing || loading || !reason.trim()}
                  >
                    {processing ? (
                      <>
                        <div
                          className="spinner-border spinner-border-sm me-2"
                          role="status"
                        >
                          <span className="visually-hidden">Loading...</span>
                        </div>
                        Processing...
                      </>
                    ) : (
                      rental.totalAmount > 0
                        ? `Cancel with ${
                            refundPreview.refundAmount > 0
                              ? `Refund ${formatCurrency(refundPreview.refundAmount)}`
                              : "No Refund"
                          }`
                        : "Cancel Rental"
                    )}
                  </button>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default RentalCancellationModal;
