import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useAuth } from "../contexts/AuthContext";
import { rentalAPI, conditionCheckAPI } from "../services/api";
import { getImageUrl } from "../services/uploadService";
import { Rental, ConditionCheck } from "../types";
import ReviewItemModal from "../components/ReviewModal";
import RentalCancellationModal from "../components/RentalCancellationModal";
import ConditionCheckModal from "../components/ConditionCheckModal";
import ConditionCheckViewerModal from "../components/ConditionCheckViewerModal";
import UpdatePaymentMethodModal from "../components/UpdatePaymentMethodModal";

const Renting: 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 "";
    }
  };

  // Helper function to format date and time together
  const formatDateTime = (dateTimeString: string) => {
    const date = new Date(dateTimeString);
    return date
      .toLocaleDateString("en-US", {
        month: "2-digit",
        day: "2-digit",
        year: "numeric",
        hour: "numeric",
        minute: "2-digit",
        hour12: true,
      })
      .replace(",", "");
  };

  const { user } = useAuth();
  const navigate = useNavigate();
  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<Rental | null>(null);
  const [showConditionCheckModal, setShowConditionCheckModal] = useState(false);
  const [conditionCheckData, setConditionCheckData] = useState<{
    rental: Rental;
    checkType: string;
  } | null>(null);
  const [availableChecks, setAvailableChecks] = useState<any[]>([]);
  const [conditionChecks, setConditionChecks] = useState<ConditionCheck[]>([]);
  const [showConditionCheckViewer, setShowConditionCheckViewer] =
    useState(false);
  const [selectedConditionCheck, setSelectedConditionCheck] =
    useState<ConditionCheck | null>(null);
  const [showUpdatePaymentModal, setShowUpdatePaymentModal] = useState(false);
  const [rentalForPaymentUpdate, setRentalForPaymentUpdate] =
    useState<Rental | null>(null);

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

  useEffect(() => {
    // Only fetch condition checks for rentals that will be displayed (pending/confirmed/active)
    const displayedRentals = rentals.filter((r) =>
      ["pending", "confirmed", "active"].includes(r.displayStatus || r.status)
    );
    if (displayedRentals.length > 0) {
      const rentalIds = displayedRentals.map((r) => r.id);
      fetchConditionChecks(displayedRentals);
      fetchAvailableChecks(rentalIds);
    } else {
      setConditionChecks([]);
      setAvailableChecks([]);
    }
  }, [rentals]);

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

  const fetchAvailableChecks = async (rentalIds: string[]) => {
    try {
      const response = await conditionCheckAPI.getAvailableChecks(rentalIds);
      const checks = Array.isArray(response.data.availableChecks)
        ? response.data.availableChecks
        : [];
      setAvailableChecks(checks);
    } catch (err: any) {
      console.error("Failed to fetch available checks:", err);
      setAvailableChecks([]);
    }
  };

  const fetchConditionChecks = async (rentalsToFetch: Rental[]) => {
    try {
      if (rentalsToFetch.length === 0) {
        setConditionChecks([]);
        return;
      }
      const rentalIds = rentalsToFetch.map((r) => r.id);
      const response = await conditionCheckAPI.getBatchConditionChecks(rentalIds);
      setConditionChecks(response.data.conditionChecks || []);
    } catch (err: any) {
      console.error("Failed to fetch condition checks:", err);
      setConditionChecks([]);
    }
  };

  const handleCancelClick = (rental: Rental) => {
    setRentalToCancel(rental);
    setShowCancelModal(true);
  };

  const handleCancellationComplete = (updatedRental: Rental) => {
    // Update the rental in the list
    setRentals((prev) =>
      prev.map((rental) =>
        rental.id === updatedRental.id ? updatedRental : rental
      )
    );
    setShowCancelModal(false);
    setRentalToCancel(null);
  };

  const handleUpdatePaymentClick = (rental: Rental) => {
    setRentalForPaymentUpdate(rental);
    setShowUpdatePaymentModal(true);
  };

  const handlePaymentMethodUpdated = () => {
    // Refresh rentals to get updated data
    fetchRentals();
    setShowUpdatePaymentModal(false);
    setRentalForPaymentUpdate(null);
  };

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

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

  const handleConditionCheck = (rental: Rental, checkType: string) => {
    setConditionCheckData({ rental, checkType });
    setShowConditionCheckModal(true);
  };

  const handleConditionCheckSuccess = () => {
    // Refetch condition checks for displayed rentals
    const displayedRentals = rentals.filter((r) =>
      ["pending", "confirmed", "active"].includes(r.displayStatus || r.status)
    );
    const rentalIds = displayedRentals.map((r) => r.id);
    fetchAvailableChecks(rentalIds);
    fetchConditionChecks(displayedRentals);
  };

  const handleViewConditionCheck = (check: ConditionCheck) => {
    setSelectedConditionCheck(check);
    setShowConditionCheckViewer(true);
  };

  const getAvailableChecksForRental = (rentalId: string) => {
    if (!Array.isArray(availableChecks)) return [];
    return availableChecks.filter(
      (check) =>
        check.rentalId === rentalId &&
        (check.checkType === "rental_start_renter" ||
          check.checkType === "rental_end_renter")
    );
  };

  const getCompletedChecksForRental = (rentalId: string) => {
    if (!Array.isArray(conditionChecks)) return [];
    return conditionChecks.filter(
      (check) =>
        check.rentalId === rentalId &&
        (check.checkType === "pre_rental_owner" ||
          check.checkType === "rental_start_renter" ||
          check.checkType === "rental_end_renter")
    );
  };

  // Filter rentals - show only active rentals (declined go to history)
  // Use displayStatus for filtering as it includes computed "active" status
  const renterActiveRentals = rentals.filter((r) =>
    ["pending", "confirmed", "active"].includes(r.displayStatus || 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>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?.imageFilenames &&
                    rental.item.imageFilenames[0] && (
                      <img
                        src={getImageUrl(rental.item.imageFilenames[0], 'thumbnail')}
                        className="card-img-top"
                        alt={rental.item.name}
                        onError={(e) => {
                          const target = e.currentTarget;
                          if (!target.dataset.fallback && rental.item) {
                            target.dataset.fallback = 'true';
                            target.src = getImageUrl(rental.item.imageFilenames[0], 'original');
                          }
                        }}
                        style={{
                          height: "200px",
                          objectFit: "contain",
                          backgroundColor: "#f8f9fa",
                        }}
                      />
                    )}
                  <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.displayStatus || rental.status) === "active"
                            ? "bg-success"
                            : (rental.displayStatus || rental.status) === "pending"
                            ? "bg-warning"
                            : (rental.displayStatus || rental.status) === "confirmed"
                            ? "bg-info"
                            : (rental.displayStatus || rental.status) === "declined"
                            ? "bg-secondary"
                            : "bg-danger"
                        }`}
                      >
                        {(rental.displayStatus || rental.status) === "pending"
                          ? "Awaiting Owner Approval"
                          : (rental.displayStatus || rental.status) === "confirmed"
                          ? "Confirmed & Paid"
                          : (rental.displayStatus || rental.status) === "declined"
                          ? "Declined by Owner"
                          : (rental.displayStatus || rental.status).charAt(0).toUpperCase() +
                            (rental.displayStatus || rental.status).slice(1)}
                      </span>
                    </div>

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

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

                    {rental.owner && (
                      <p className="mb-1 text-dark">
                        <strong>Owner:</strong>{" "}
                        <span
                          onClick={() => navigate(`/users/${rental.ownerId}`)}
                          style={{ cursor: "pointer" }}
                        >
                          {rental.owner.firstName} {rental.owner.lastName}
                        </span>
                      </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 === "declined" && rental.declineReason && (
                      <div className="alert alert-warning mt-2 mb-1 p-2 small">
                        <strong>Decline reason:</strong> {rental.declineReason}
                      </div>
                    )}

                    {rental.status === "cancelled" && (
                      <>
                        {rental.refundAmount !== undefined && (
                          <div className="alert alert-info mt-2 mb-1 p-2 small">
                            <strong>
                              <i className="bi bi-arrow-return-left me-1"></i>
                              Refund:
                            </strong>{" "}
                            ${rental.refundAmount?.toFixed(2) || "0.00"}
                            {rental.refundProcessedAt && (
                              <small className="d-block text-muted mt-1">
                                Processed:{" "}
                                {new Date(
                                  rental.refundProcessedAt
                                ).toLocaleDateString()}
                              </small>
                            )}
                            {rental.refundReason && (
                              <small className="d-block mt-1">
                                {rental.refundReason}
                              </small>
                            )}
                          </div>
                        )}
                      </>
                    )}

                    {/* Payment Failed Alert */}
                    {(rental.displayStatus || rental.status) === "pending" &&
                      rental.paymentStatus === "pending" &&
                      rental.paymentFailedNotifiedAt && (
                        <div className="alert alert-warning py-2 mb-3">
                          <div className="d-flex align-items-center justify-content-between">
                            <small>
                              <strong>Payment issue:</strong>{" "}
                              {rental.paymentFailedReason ||
                                "Please update your payment method so the owner can approve your request."}
                            </small>
                            <button
                              className="btn btn-sm btn-warning ms-2"
                              onClick={() => handleUpdatePaymentClick(rental)}
                            >
                              Update Payment
                            </button>
                          </div>
                        </div>
                      )}

                    {/* 3DS Authentication Required Alert */}
                    {rental.paymentStatus === "requires_action" && (
                      <div className="alert alert-warning py-2 mb-3">
                        <div className="d-flex align-items-center justify-content-between">
                          <div>
                            <i className="bi bi-shield-lock me-2"></i>
                            <strong>Payment authentication required</strong>
                            <p className="mb-0 small text-muted mt-1">
                              Your bank requires additional verification to
                              complete this payment.
                            </p>
                          </div>
                          <button
                            className="btn btn-warning btn-sm ms-3"
                            onClick={() =>
                              navigate(`/complete-payment/${rental.id}`)
                            }
                          >
                            Complete Payment
                          </button>
                        </div>
                      </div>
                    )}

                    <div className="d-flex flex-column gap-2 mt-3">
                      <div className="d-flex gap-2">
                        {((rental.displayStatus || rental.status) === "pending" ||
                          (rental.displayStatus || rental.status) === "confirmed") && (
                          <button
                            className="btn btn-sm btn-danger"
                            onClick={() => handleCancelClick(rental)}
                          >
                            Cancel
                          </button>
                        )}
                        {(rental.displayStatus || rental.status) === "active" &&
                          !rental.itemRating &&
                          !rental.itemReviewSubmittedAt && (
                            <button
                              className="btn btn-sm btn-primary"
                              onClick={() => handleReviewClick(rental)}
                            >
                              Review
                            </button>
                          )}
                      </div>

                      {/* Condition Check Status */}
                      {getCompletedChecksForRental(rental.id).length > 0 && (
                        <div className="mb-2">
                          {getCompletedChecksForRental(rental.id).map(
                            (check) => (
                              <button
                                key={`${rental.id}-${check.checkType}-status`}
                                className="btn btn-link text-success small p-0 text-decoration-none d-block"
                                onClick={() => handleViewConditionCheck(check)}
                              >
                                {check.checkType === "pre_rental_owner"
                                  ? "Owner's Pre-Rental Condition"
                                  : check.checkType === "rental_start_renter"
                                  ? "Rental Start Condition Noted"
                                  : "Rental End Condition Noted"}
                                <small className="text-muted ms-2">
                                  {new Date(
                                    check.createdAt
                                  ).toLocaleDateString()}
                                </small>
                              </button>
                            )
                          )}
                        </div>
                      )}

                      {/* Condition Check Buttons */}
                      {getAvailableChecksForRental(rental.id).map((check) => (
                        <button
                          key={`${rental.id}-${check.checkType}`}
                          className="btn btn-sm btn-outline-primary"
                          onClick={() =>
                            handleConditionCheck(rental, check.checkType)
                          }
                        >
                          <i className="bi bi-camera me-2" />
                          {check.checkType === "rental_start_renter"
                            ? "Submit Rental Start Condition"
                            : "Submit Rental End Condition"}
                        </button>
                      ))}

                      {/* Review Status */}
                      {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}
        />
      )}

      {rentalToCancel && (
        <RentalCancellationModal
          show={showCancelModal}
          onHide={() => {
            setShowCancelModal(false);
            setRentalToCancel(null);
          }}
          rental={rentalToCancel}
          onCancellationComplete={handleCancellationComplete}
        />
      )}

      {/* Condition Check Modal */}
      {conditionCheckData && (
        <ConditionCheckModal
          show={showConditionCheckModal}
          onHide={() => {
            setShowConditionCheckModal(false);
            setConditionCheckData(null);
          }}
          rentalId={conditionCheckData.rental.id}
          checkType={conditionCheckData.checkType}
          itemName={conditionCheckData.rental.item?.name || "Item"}
          onSuccess={handleConditionCheckSuccess}
        />
      )}

      {/* Condition Check Viewer Modal */}
      <ConditionCheckViewerModal
        show={showConditionCheckViewer}
        onHide={() => {
          setShowConditionCheckViewer(false);
          setSelectedConditionCheck(null);
        }}
        conditionCheck={selectedConditionCheck}
      />

      {/* Update Payment Method Modal */}
      {rentalForPaymentUpdate && (
        <UpdatePaymentMethodModal
          show={showUpdatePaymentModal}
          onHide={() => {
            setShowUpdatePaymentModal(false);
            setRentalForPaymentUpdate(null);
          }}
          rentalId={rentalForPaymentUpdate.id}
          itemName={rentalForPaymentUpdate.item?.name || "Item"}
          onSuccess={handlePaymentMethodUpdated}
        />
      )}
    </div>
  );
};

export default Renting;
