import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { useAuth } from "../contexts/AuthContext";
import { rentalAPI } from "../services/api";
import { Rental } from "../types";
import ReviewItemModal from "../components/ReviewModal";
import ConfirmationModal from "../components/ConfirmationModal";

const MyRentals: React.FC = () => {
  // Helper function to format time
  const formatTime = (timeString?: string) => {
    if (!timeString || timeString.trim() === "") return "";
    try {
      const [hour, minute] = timeString.split(":");
      const hourNum = parseInt(hour);
      const hour12 = hourNum === 0 ? 12 : hourNum > 12 ? hourNum - 12 : hourNum;
      const period = hourNum < 12 ? "AM" : "PM";
      return `${hour12}:${minute} ${period}`;
    } catch (error) {
      return "";
    }
  };

  const { user } = useAuth();
  const [rentals, setRentals] = useState<Rental[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showReviewModal, setShowReviewModal] = useState(false);
  const [selectedRental, setSelectedRental] = useState<Rental | null>(null);
  const [showCancelModal, setShowCancelModal] = useState(false);
  const [rentalToCancel, setRentalToCancel] = useState<string | null>(null);
  const [cancelling, setCancelling] = useState(false);

  useEffect(() => {
    fetchRentals();
  }, []);

  const fetchRentals = async () => {
    try {
      const response = await rentalAPI.getMyRentals();
      setRentals(response.data);
    } catch (err: any) {
      setError(err.response?.data?.message || "Failed to fetch rentals");
    } finally {
      setLoading(false);
    }
  };

  const handleCancelClick = (rentalId: string) => {
    setRentalToCancel(rentalId);
    setShowCancelModal(true);
  };

  const confirmCancelRental = async () => {
    if (!rentalToCancel) return;

    setCancelling(true);
    try {
      await rentalAPI.updateRentalStatus(rentalToCancel, "cancelled");
      fetchRentals();
      setShowCancelModal(false);
      setRentalToCancel(null);
    } catch (err: any) {
      alert("Failed to cancel rental");
    } finally {
      setCancelling(false);
    }
  };

  const handleReviewClick = (rental: Rental) => {
    setSelectedRental(rental);
    setShowReviewModal(true);
  };

  const handleReviewSuccess = () => {
    fetchRentals();
    alert("Thank you for your review!");
  };

  // Filter rentals - only show active rentals (pending, confirmed, active)
  const renterActiveRentals = rentals.filter((r) =>
    ["pending", "confirmed", "active"].includes(r.status)
  );

  if (loading) {
    return (
      <div className="container mt-5">
        <div className="text-center">
          <div className="spinner-border" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mt-5">
        <div className="alert alert-danger" role="alert">
          {error}
        </div>
      </div>
    );
  }

  return (
    <div className="container mt-4">
      <h1>My Rentals</h1>

      {renterActiveRentals.length === 0 ? (
        <div className="text-center py-5">
          <h5 className="text-muted">No Active Rental Requests</h5>
          <p className="text-muted">
            You don't have any rental requests at the moment.
          </p>
          <Link to="/items" className="btn btn-primary">
            Browse Items to Rent
          </Link>
        </div>
      ) : (
        <div className="row">
          {renterActiveRentals.map((rental) => (
            <div key={rental.id} className="col-md-6 col-lg-4 mb-4">
              <Link
                to={rental.item ? `/items/${rental.item.id}` : "#"}
                className="text-decoration-none"
                onClick={(e: React.MouseEvent<HTMLAnchorElement>) => {
                  const target = e.target as HTMLElement;
                  if (!rental.item || target.closest("button")) {
                    e.preventDefault();
                  }
                }}
              >
                <div
                  className="card h-100"
                  style={{ cursor: rental.item ? "pointer" : "default" }}
                >
                  {rental.item?.images && rental.item.images[0] && (
                    <img
                      src={rental.item.images[0]}
                      className="card-img-top"
                      alt={rental.item.name}
                      style={{ height: "200px", objectFit: "cover" }}
                    />
                  )}
                  <div className="card-body">
                    <h5 className="card-title text-dark">
                      {rental.item ? rental.item.name : "Item Unavailable"}
                    </h5>

                    <div className="mb-2">
                      <span
                        className={`badge ${
                          rental.status === "active"
                            ? "bg-success"
                            : rental.status === "pending"
                            ? "bg-warning"
                            : rental.status === "confirmed"
                            ? "bg-info"
                            : "bg-danger"
                        }`}
                      >
                        {rental.status.charAt(0).toUpperCase() +
                          rental.status.slice(1)}
                      </span>
                    </div>

                    <p className="mb-1 text-dark">
                      <strong>Rental Period:</strong>
                      <br />
                      <strong>Start:</strong>{" "}
                      {new Date(rental.startDateTime).toLocaleString()}
                      <br />
                      <strong>End:</strong>{" "}
                      {new Date(rental.endDateTime).toLocaleString()}
                    </p>

                    <p className="mb-1 text-dark">
                      <strong>Total:</strong> ${rental.totalAmount}
                    </p>

                    {rental.owner && (
                      <p className="mb-1 text-dark">
                        <strong>Owner:</strong> {rental.owner.firstName}{" "}
                        {rental.owner.lastName}
                      </p>
                    )}

                    {rental.renterPrivateMessage &&
                      rental.renterReviewVisible && (
                        <div className="alert alert-info mt-2 mb-2 p-2 small">
                          <strong>
                            <i className="bi bi-envelope-fill me-1"></i>Private
                            Note from Owner:
                          </strong>
                          <br />
                          {rental.renterPrivateMessage}
                        </div>
                      )}

                    {rental.status === "cancelled" &&
                      rental.rejectionReason && (
                        <div className="alert alert-warning mt-2 mb-1 p-2 small">
                          <strong>Rejection reason:</strong>{" "}
                          {rental.rejectionReason}
                        </div>
                      )}

                    <div className="d-flex gap-2 mt-3">
                      {rental.status === "pending" && (
                        <button
                          className="btn btn-sm btn-danger"
                          onClick={() => handleCancelClick(rental.id)}
                        >
                          Cancel
                        </button>
                      )}
                      {rental.status === "active" &&
                        !rental.itemRating &&
                        !rental.itemReviewSubmittedAt && (
                          <button
                            className="btn btn-sm btn-primary"
                            onClick={() => handleReviewClick(rental)}
                          >
                            Review
                          </button>
                        )}
                      {rental.itemReviewSubmittedAt &&
                        !rental.itemReviewVisible && (
                          <div className="text-info small">
                            <i className="bi bi-clock me-1"></i>
                            Review Submitted
                          </div>
                        )}
                      {rental.itemReviewVisible && rental.itemRating && (
                        <div className="text-success small">
                          <i className="bi bi-check-circle-fill me-1"></i>
                          Review Published ({rental.itemRating}/5)
                        </div>
                      )}
                      {rental.status === "completed" &&
                        rental.rating &&
                        !rental.itemRating && (
                          <div className="text-success small">
                            <i className="bi bi-check-circle-fill me-1"></i>
                            Reviewed ({rental.rating}/5)
                          </div>
                        )}
                    </div>
                  </div>
                </div>
              </Link>
            </div>
          ))}
        </div>
      )}

      {/* Review Modal */}
      {selectedRental && (
        <ReviewItemModal
          show={showReviewModal}
          onClose={() => {
            setShowReviewModal(false);
            setSelectedRental(null);
          }}
          rental={selectedRental}
          onSuccess={handleReviewSuccess}
        />
      )}

      <ConfirmationModal
        show={showCancelModal}
        onClose={() => {
          setShowCancelModal(false);
          setRentalToCancel(null);
        }}
        onConfirm={confirmCancelRental}
        title="Cancel Rental"
        message="Are you sure you want to cancel this rental? This action cannot be undone."
        confirmText="Yes, Cancel Rental"
        cancelText="Keep Rental"
        confirmButtonClass="btn-danger"
        loading={cancelling}
      />
    </div>
  );
};

export default MyRentals;
