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

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);

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

  useEffect(() => {
    if (rentals.length > 0) {
      fetchConditionChecks();
    }
  }, [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 () => {
    try {
      const response = await conditionCheckAPI.getAvailableChecks();
      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 () => {
    try {
      // Fetch condition checks for all rentals
      const allChecks: any[] = [];
      for (const rental of rentals) {
        try {
          const response = await conditionCheckAPI.getConditionChecks(
            rental.id
          );
          const checks = Array.isArray(response.data.conditionChecks)
            ? response.data.conditionChecks
            : [];
          allChecks.push(...checks);
        } catch (err) {
          // Continue even if one rental fails
          console.error(`Failed to fetch checks for rental ${rental.id}:`, err);
        }
      }
      setConditionChecks(allChecks);
    } 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 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 = () => {
    fetchAvailableChecks();
    fetchConditionChecks();
  };

  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 === "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>
                        )}
                      </>
                    )}

                    <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 === "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}
      />
    </div>
  );
};

export default Renting;
