import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { Item, Rental } from "../types";
import { useAuth } from "../contexts/AuthContext";
import { itemAPI, rentalAPI } from "../services/api";
import { getImageUrl } from "../services/uploadService";
import GoogleMapWithRadius from "../components/GoogleMapWithRadius";
import ItemReviews from "../components/ItemReviews";
import ConfirmationModal from "../components/ConfirmationModal";
import Avatar from "../components/Avatar";

// Helper function to validate date selection
const validateDates = (
  startDate: Date | null,
  startTime: string,
  endDate: Date | null,
  endTime: string
): { isValid: boolean; error: string | null } => {
  if (!startDate || !endDate || !startTime || !endTime) {
    return { isValid: false, error: null }; // No error, just incomplete
  }

  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

  // Check if start date is in the past
  const startDateOnly = new Date(
    startDate.getFullYear(),
    startDate.getMonth(),
    startDate.getDate()
  );
  if (startDateOnly < today) {
    return { isValid: false, error: "Start date cannot be in the past" };
  }

  // Check if start datetime is in the past (for today's date)
  if (startDateOnly.getTime() === today.getTime()) {
    const [startHour] = startTime.split(":").map(Number);
    const startDateTime = new Date(startDate);
    startDateTime.setHours(startHour, 0, 0, 0);
    if (startDateTime < now) {
      return { isValid: false, error: "Start time cannot be in the past" };
    }
  }

  // Check if end date is before start date
  const endDateOnly = new Date(
    endDate.getFullYear(),
    endDate.getMonth(),
    endDate.getDate()
  );
  if (endDateOnly < startDateOnly) {
    return { isValid: false, error: "End date must be on or after start date" };
  }

  // Check if end time is after start time (same day scenario)
  if (startDateOnly.getTime() === endDateOnly.getTime()) {
    if (endTime <= startTime) {
      return { isValid: false, error: "End time must be after start time" };
    }
  }

  return { isValid: true, error: null };
};

const ItemDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  const [item, setItem] = useState<Item | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedImage, setSelectedImage] = useState(0);
  const [isAlreadyRenting, setIsAlreadyRenting] = useState(false);
  const [rentalDates, setRentalDates] = useState<{
    startDate: Date | null;
    startTime: string;
    endDate: Date | null;
    endTime: string;
  }>({
    startDate: null,
    startTime: "",
    endDate: null,
    endTime: "",
  });
  const [dateValidationError, setDateValidationError] = useState<string | null>(
    null
  );
  const [totalCost, setTotalCost] = useState(0);
  const [costLoading, setCostLoading] = useState(false);
  const [costError, setCostError] = useState<string | null>(null);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [confirmAction, setConfirmAction] = useState<
    "delete" | "restore" | null
  >(null);
  const [deletionReason, setDeletionReason] = useState("");

  useEffect(() => {
    fetchItem();
  }, [id]);

  useEffect(() => {
    if (user) {
      checkIfAlreadyRenting();
    } else {
      setIsAlreadyRenting(false);
    }
  }, [id, user]);

  const fetchItem = async () => {
    try {
      const response = await itemAPI.getItem(id!);
      setItem(response.data);
    } catch (err: any) {
      setError(err.response?.data?.message || "Failed to fetch item");
    } finally {
      setLoading(false);
    }
  };

  const checkIfAlreadyRenting = async () => {
    try {
      const response = await rentalAPI.getRentals();
      const rentals: Rental[] = response.data;
      // Check if user has an active rental for this item
      const hasActiveRental = rentals.some(
        (rental) =>
          rental.item?.id === id &&
          ["pending", "confirmed", "active"].includes(rental.status)
      );
      setIsAlreadyRenting(hasActiveRental);
    } catch (err) {
      console.error("Failed to check rental status:", err);
    }
  };

  const handleEdit = () => {
    navigate(`/items/${id}/edit`);
  };

  const handleAdminSoftDelete = () => {
    setConfirmAction("delete");
    setShowConfirmModal(true);
  };

  const handleAdminRestore = () => {
    setConfirmAction("restore");
    setShowConfirmModal(true);
  };

  const handleConfirmAction = async () => {
    try {
      setDeleteLoading(true);
      setDeleteError(null);

      if (confirmAction === "delete") {
        await itemAPI.adminSoftDeleteItem(id!, deletionReason);
      } else if (confirmAction === "restore") {
        await itemAPI.adminRestoreItem(id!);
      }

      await fetchItem(); // Refresh the item to show updated status
      setShowConfirmModal(false);
      setConfirmAction(null);
      setDeletionReason("");
    } catch (err: any) {
      const errorMessage =
        err.response?.data?.error || `Failed to ${confirmAction} item`;
      setDeleteError(errorMessage);
      console.error(`Admin ${confirmAction} failed:`, err);
      setShowConfirmModal(false);
      setConfirmAction(null);
      setDeletionReason("");
    } finally {
      setDeleteLoading(false);
    }
  };

  const handleCancelConfirm = () => {
    setShowConfirmModal(false);
    setConfirmAction(null);
    setDeletionReason("");
  };

  const handleRent = () => {
    const startDateTime = combineDateTimeToISO(
      rentalDates.startDate,
      rentalDates.startTime
    );
    const endDateTime = combineDateTimeToISO(
      rentalDates.endDate,
      rentalDates.endTime
    );
    if (!startDateTime || !endDateTime) return;
    const params = new URLSearchParams({
      startDateTime,
      endDateTime,
    });
    navigate(`/items/${id}/rent?${params.toString()}`);
  };

  const handleCopyLink = async () => {
    const shareUrl = `${window.location.origin}/items/${item?.id}`;

    try {
      await navigator.clipboard.writeText(shareUrl);
    } catch (err) {
      console.error("Copy to clipboard failed:", err);
    }
  };

  // Helper to combine date and time into ISO string
  const combineDateTimeToISO = (
    date: Date | null,
    time: string
  ): string | null => {
    if (!date || !time) return null;
    const [hours] = time.split(":").map(Number);
    const combined = new Date(date);
    combined.setHours(hours, 0, 0, 0);
    return combined.toISOString();
  };

  const calculateTotalCost = async () => {
    const startDateTime = combineDateTimeToISO(
      rentalDates.startDate,
      rentalDates.startTime
    );
    const endDateTime = combineDateTimeToISO(
      rentalDates.endDate,
      rentalDates.endTime
    );

    if (!item || !startDateTime || !endDateTime) {
      setTotalCost(0);
      return;
    }

    try {
      setCostLoading(true);
      setCostError(null);

      const response = await rentalAPI.getRentalCostPreview({
        itemId: item.id,
        startDateTime,
        endDateTime,
      });

      setTotalCost(response.data.baseAmount);
    } catch (err: any) {
      setCostError(err.response?.data?.error || "Failed to calculate cost");
      setTotalCost(0);
    } finally {
      setCostLoading(false);
    }
  };

  // Generate time options for dropdown based on item availability for a given date
  const generateTimeOptions = (
    selectedDate: Date | null
  ): { value: string; label: string }[] => {
    const options: { value: string; label: string }[] = [];

    let availableAfterHour = 0;
    let availableBeforeHour = 23;

    if (item && selectedDate) {
      const dayName = selectedDate
        .toLocaleDateString("en-US", { weekday: "long" })
        .toLowerCase() as
        | "sunday"
        | "monday"
        | "tuesday"
        | "wednesday"
        | "thursday"
        | "friday"
        | "saturday";

      // Use day-specific times if available
      if (
        item.specifyTimesPerDay &&
        item.weeklyTimes &&
        item.weeklyTimes[dayName]
      ) {
        const dayTimes = item.weeklyTimes[dayName];
        availableAfterHour = parseInt(
          dayTimes.availableAfter.split(":")[0],
          10
        );
        availableBeforeHour = parseInt(
          dayTimes.availableBefore.split(":")[0],
          10
        );
      }
      // Otherwise use global times
      else if (item.availableAfter && item.availableBefore) {
        availableAfterHour = parseInt(item.availableAfter.split(":")[0], 10);
        availableBeforeHour = parseInt(item.availableBefore.split(":")[0], 10);
      }
    }

    for (let hour = availableAfterHour; hour <= availableBeforeHour; hour++) {
      const hourStr = hour.toString().padStart(2, "0");
      const period = hour >= 12 ? "PM" : "AM";
      const displayHour = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
      options.push({
        value: `${hourStr}:00`,
        label: `${displayHour}:00 ${period}`,
      });
    }

    return options;
  };

  useEffect(() => {
    calculateTotalCost();
  }, [rentalDates, item]);

  // Validate dates whenever they change
  useEffect(() => {
    const validation = validateDates(
      rentalDates.startDate,
      rentalDates.startTime,
      rentalDates.endDate,
      rentalDates.endTime
    );
    setDateValidationError(validation.error);
  }, [rentalDates]);

  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 || !item) {
    return (
      <div className="container mt-5">
        <div className="alert alert-danger" role="alert">
          {error || "Item not found"}
        </div>
      </div>
    );
  }

  const isOwner = user?.id === item.ownerId;
  const isAdmin = user?.role === "admin";

  return (
    <div className="container mt-5">
      <div className="row justify-content-center">
        <div className="col-md-10">
          {/* Deleted Status Indicator for Admins */}
          {item.isDeleted && isAdmin && (
            <div className="alert alert-warning mb-3" role="alert">
              <i className="bi bi-exclamation-triangle-fill me-2"></i>
              <strong>Item Soft Deleted</strong> - This item is hidden from
              public listings.
              {item.deleter && (
                <span className="ms-2">
                  Deleted by {item.deleter.firstName} {item.deleter.lastName}
                </span>
              )}
              {item.deletedAt && (
                <span className="ms-2">
                  on {new Date(item.deletedAt).toLocaleDateString()}
                </span>
              )}
              {item.deletionReason && (
                <div className="mt-2">
                  <strong>Reason:</strong> {item.deletionReason}
                </div>
              )}
            </div>
          )}

          {/* Delete Error Alert */}
          {deleteError && (
            <div className="alert alert-danger mb-3" role="alert">
              {deleteError}
            </div>
          )}

          {/* Action Buttons (Owner Edit + Admin Soft Delete/Restore) */}
          {(isOwner || isAdmin) && (
            <div className="d-flex justify-content-end gap-2 mb-3">
              {isOwner && (
                <button
                  className="btn btn-outline-primary"
                  onClick={handleEdit}
                >
                  <i className="bi bi-pencil me-2"></i>
                  Edit Listing
                </button>
              )}
              {isAdmin && !item.isDeleted && (
                <button
                  className="btn btn-outline-danger"
                  onClick={handleAdminSoftDelete}
                  disabled={deleteLoading}
                >
                  {deleteLoading ? (
                    <>
                      <span
                        className="spinner-border spinner-border-sm me-2"
                        role="status"
                        aria-hidden="true"
                      ></span>
                      Deleting...
                    </>
                  ) : (
                    <>
                      <i className="bi bi-trash me-2"></i>
                      Delete
                    </>
                  )}
                </button>
              )}
              {isAdmin && item.isDeleted && (
                <button
                  className="btn btn-outline-success"
                  onClick={handleAdminRestore}
                  disabled={deleteLoading}
                >
                  {deleteLoading ? (
                    <>
                      <span
                        className="spinner-border spinner-border-sm me-2"
                        role="status"
                        aria-hidden="true"
                      ></span>
                      Restoring...
                    </>
                  ) : (
                    <>
                      <i className="bi bi-arrow-counterclockwise me-2"></i>
                      Restore
                    </>
                  )}
                </button>
              )}
            </div>
          )}

          <div className="row">
            <div className="col-md-8">
              {/* Images */}
              {item.imageFilenames.length > 0 ? (
                <div className="mb-4">
                  <img
                    src={getImageUrl(
                      item.imageFilenames[selectedImage],
                      "medium"
                    )}
                    alt={item.name}
                    className="img-fluid rounded mb-3"
                    loading="lazy"
                    onError={(e) => {
                      const target = e.currentTarget;
                      if (!target.dataset.fallback) {
                        target.dataset.fallback = "true";
                        target.src = getImageUrl(
                          item.imageFilenames[selectedImage],
                          "original"
                        );
                      }
                    }}
                    style={{
                      width: "100%",
                      maxHeight: "500px",
                      objectFit: "contain",
                      backgroundColor: "#f8f9fa",
                    }}
                  />
                  {item.imageFilenames.length > 1 && (
                    <div className="d-flex gap-2 overflow-auto justify-content-center">
                      {item.imageFilenames.map((image, index) => (
                        <img
                          key={index}
                          src={getImageUrl(image, "thumbnail")}
                          alt={`${item.name} ${index + 1}`}
                          className={`rounded cursor-pointer ${
                            selectedImage === index
                              ? "border border-primary"
                              : ""
                          }`}
                          loading="lazy"
                          onError={(e) => {
                            const target = e.currentTarget;
                            if (!target.dataset.fallback) {
                              target.dataset.fallback = "true";
                              target.src = getImageUrl(image, "original");
                            }
                          }}
                          style={{
                            width: "80px",
                            height: "80px",
                            objectFit: "cover",
                            cursor: "pointer",
                          }}
                          onClick={() => setSelectedImage(index)}
                        />
                      ))}
                    </div>
                  )}
                </div>
              ) : (
                <div
                  className="bg-light rounded d-flex align-items-center justify-content-center mb-4"
                  style={{ height: "400px" }}
                >
                  <span className="text-muted">No image available</span>
                </div>
              )}
              {/* Item Name */}
              <div className="d-flex align-items-center justify-content-between mb-3">
                <h1 className="mb-0">{item.name}</h1>
                <button
                  className="btn btn-outline-secondary btn-sm"
                  onClick={handleCopyLink}
                  aria-label="Copy link to this item"
                >
                  <i className="bi bi-link-45deg me-2"></i>
                  Copy Link
                </button>
              </div>

              {/* Owner Info */}
              {item.owner && (
                <div
                  className="d-flex align-items-center mb-4"
                  onClick={() => navigate(`/users/${item.ownerId}`)}
                  style={{ cursor: "pointer" }}
                >
                  <Avatar user={item.owner} size="xs" className="me-2" />
                  <span className="text-muted">
                    {item.owner.firstName} {item.owner.lastName}
                  </span>
                </div>
              )}

              {/* Description (no label) */}
              <div className="mb-4">
                <p>{item.description}</p>
              </div>

              {/* Map */}
              <GoogleMapWithRadius
                latitude={item.latitude}
                longitude={item.longitude}
              />

              <ItemReviews itemId={item.id} />

              {/* Rules */}
              {item.rules && (
                <div className="mb-4">
                  <h5>Rules</h5>
                  <p>{item.rules}</p>
                </div>
              )}

              {/* Cancellation Policy */}
              <div className="mb-4">
                <h5>Cancellation Policy</h5>
                <div className="small">
                  <div className="mb-2">
                    Full refund: Cancel 48+ hours before rental start time
                  </div>
                  <div className="mb-2">
                    50% refund: Cancel 24-48 hours before rental start time
                  </div>
                  <div className="mb-2">
                    No refund: Cancel within 24 hours of rental start time
                  </div>
                  <div>Replacement Cost: ${item.replacementCost}</div>
                </div>
              </div>

              {/* Mobile Pricing Card - shown inline on mobile */}
              <div className="d-md-none mb-4" id="mobile-pricing-card">
                <div className="card sticky-pricing-card">
                  <div className="card-body text-center">
                    {(() => {
                      const hasAnyPositivePrice =
                        (item.pricePerHour !== undefined &&
                          Number(item.pricePerHour) > 0) ||
                        (item.pricePerDay !== undefined &&
                          Number(item.pricePerDay) > 0) ||
                        (item.pricePerWeek !== undefined &&
                          Number(item.pricePerWeek) > 0) ||
                        (item.pricePerMonth !== undefined &&
                          Number(item.pricePerMonth) > 0);

                      const hasAnyZeroPrice =
                        (item.pricePerHour !== undefined &&
                          Number(item.pricePerHour) === 0) ||
                        (item.pricePerDay !== undefined &&
                          Number(item.pricePerDay) === 0) ||
                        (item.pricePerWeek !== undefined &&
                          Number(item.pricePerWeek) === 0) ||
                        (item.pricePerMonth !== undefined &&
                          Number(item.pricePerMonth) === 0);

                      if (!hasAnyPositivePrice && hasAnyZeroPrice) {
                        return (
                          <div className="mb-4">
                            <h4>Free to Borrow</h4>
                          </div>
                        );
                      }

                      return (
                        <>
                          {item.pricePerHour !== undefined &&
                            Number(item.pricePerHour) > 0 && (
                              <div className="mb-2">
                                <h4>
                                  ${Math.floor(Number(item.pricePerHour))}/Hour
                                </h4>
                              </div>
                            )}
                          {item.pricePerDay !== undefined &&
                            Number(item.pricePerDay) > 0 && (
                              <div className="mb-2">
                                <h4>
                                  ${Math.floor(Number(item.pricePerDay))}/Day
                                </h4>
                              </div>
                            )}
                          {item.pricePerWeek !== undefined &&
                            Number(item.pricePerWeek) > 0 && (
                              <div className="mb-2">
                                <h4>
                                  ${Math.floor(Number(item.pricePerWeek))}/Week
                                </h4>
                              </div>
                            )}
                          {item.pricePerMonth !== undefined &&
                            Number(item.pricePerMonth) > 0 && (
                              <div className="mb-2">
                                <h4>
                                  ${Math.floor(Number(item.pricePerMonth))}
                                  /Month
                                </h4>
                              </div>
                            )}
                        </>
                      );
                    })()}

                    {/* Rental Period Selection - Only show for non-owners */}
                    {!isOwner && item.isAvailable && (
                      <>
                        <hr />
                        {isAlreadyRenting && (
                          <div className="alert alert-warning py-2 mb-3" role="alert">
                            <i className="bi bi-exclamation-triangle-fill me-2"></i>
                            <small>You already have an active rental for this item</small>
                          </div>
                        )}
                        <div className="text-start">
                          {dateValidationError && (
                            <div
                              className="alert alert-danger py-2 mb-3"
                              role="alert"
                            >
                              <small>{dateValidationError}</small>
                            </div>
                          )}
                          <div className="mb-3">
                            <label className="form-label fw-medium mb-2">
                              Start
                            </label>
                            <div style={{ width: "60%" }}>
                              <DatePicker
                                selected={rentalDates.startDate}
                                onChange={(date: Date | null) =>
                                  setRentalDates((prev) => ({
                                    ...prev,
                                    startDate: date,
                                  }))
                                }
                                minDate={new Date()}
                                dateFormat="MM/dd/yyyy"
                                placeholderText="mm/dd/yyyy"
                                className="form-control form-control-lg mb-2 w-100"
                                popperProps={{ strategy: "fixed" }}
                              />
                            </div>
                            <select
                              className="form-select form-select-lg"
                              style={{ width: "60%" }}
                              value={rentalDates.startTime}
                              onChange={(e) =>
                                setRentalDates((prev) => ({
                                  ...prev,
                                  startTime: e.target.value,
                                }))
                              }
                              disabled={!rentalDates.startDate}
                            >
                              <option value="">Pickup Time</option>
                              {generateTimeOptions(rentalDates.startDate).map(
                                (option) => (
                                  <option
                                    key={option.value}
                                    value={option.value}
                                  >
                                    {option.label}
                                  </option>
                                )
                              )}
                            </select>
                          </div>

                          <div className="mb-3">
                            <label className="form-label fw-medium mb-2">
                              End
                            </label>
                            <div style={{ width: "60%" }}>
                              <DatePicker
                                selected={rentalDates.endDate}
                                onChange={(date: Date | null) =>
                                  setRentalDates((prev) => ({
                                    ...prev,
                                    endDate: date,
                                  }))
                                }
                                minDate={rentalDates.startDate || new Date()}
                                dateFormat="MM/dd/yyyy"
                                placeholderText="mm/dd/yyyy"
                                className="form-control form-control-lg mb-2 w-100"
                                popperProps={{ strategy: "fixed" }}
                              />
                            </div>
                            <select
                              className="form-select form-select-lg"
                              style={{ width: "60%" }}
                              value={rentalDates.endTime}
                              onChange={(e) =>
                                setRentalDates((prev) => ({
                                  ...prev,
                                  endTime: e.target.value,
                                }))
                              }
                              disabled={!rentalDates.endDate}
                            >
                              <option value="">Return Time</option>
                              {generateTimeOptions(rentalDates.endDate).map(
                                (option) => (
                                  <option
                                    key={option.value}
                                    value={option.value}
                                  >
                                    {option.label}
                                  </option>
                                )
                              )}
                            </select>
                          </div>

                          {rentalDates.startDate &&
                            rentalDates.startTime &&
                            rentalDates.endDate &&
                            rentalDates.endTime &&
                            !dateValidationError && (
                              <div className="mb-3 p-2 bg-light rounded text-center">
                                {costLoading ? (
                                  <div
                                    className="spinner-border spinner-border-sm"
                                    role="status"
                                  >
                                    <span className="visually-hidden">
                                      Calculating...
                                    </span>
                                  </div>
                                ) : costError ? (
                                  <small className="text-danger">
                                    {costError}
                                  </small>
                                ) : totalCost > 0 ? (
                                  <strong>Total: ${totalCost}</strong>
                                ) : null}
                              </div>
                            )}
                        </div>
                      </>
                    )}

                    {/* Action Buttons */}
                    {!isOwner && item.isAvailable && (
                      <div className="d-grid">
                        <button
                          className="btn btn-primary btn-lg"
                          onClick={handleRent}
                          disabled={
                            !rentalDates.startDate ||
                            !rentalDates.startTime ||
                            !rentalDates.endDate ||
                            !rentalDates.endTime ||
                            !!dateValidationError
                          }
                        >
                          Rent Now
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>

            {/* Right Side - Sticky Pricing Card (hidden on mobile, shown on desktop) */}
            <div className="col-md-4 d-none d-md-block">
              <div
                className="card sticky-pricing-card"
                id="pricing-card"
                style={{
                  position: "sticky",
                  top: "20px",
                  alignSelf: "flex-start",
                }}
              >
                <div className="card-body text-center">
                  {(() => {
                    const hasAnyPositivePrice =
                      (item.pricePerHour !== undefined &&
                        Number(item.pricePerHour) > 0) ||
                      (item.pricePerDay !== undefined &&
                        Number(item.pricePerDay) > 0) ||
                      (item.pricePerWeek !== undefined &&
                        Number(item.pricePerWeek) > 0) ||
                      (item.pricePerMonth !== undefined &&
                        Number(item.pricePerMonth) > 0);

                    const hasAnyZeroPrice =
                      (item.pricePerHour !== undefined &&
                        Number(item.pricePerHour) === 0) ||
                      (item.pricePerDay !== undefined &&
                        Number(item.pricePerDay) === 0) ||
                      (item.pricePerWeek !== undefined &&
                        Number(item.pricePerWeek) === 0) ||
                      (item.pricePerMonth !== undefined &&
                        Number(item.pricePerMonth) === 0);

                    if (!hasAnyPositivePrice && hasAnyZeroPrice) {
                      return (
                        <div className="mb-4">
                          <h4>Free to Borrow</h4>
                        </div>
                      );
                    }

                    return (
                      <>
                        {item.pricePerHour !== undefined &&
                          Number(item.pricePerHour) > 0 && (
                            <div className="mb-2">
                              <h4>
                                ${Math.floor(Number(item.pricePerHour))}/Hour
                              </h4>
                            </div>
                          )}
                        {item.pricePerDay !== undefined &&
                          Number(item.pricePerDay) > 0 && (
                            <div className="mb-2">
                              <h4>
                                ${Math.floor(Number(item.pricePerDay))}/Day
                              </h4>
                            </div>
                          )}
                        {item.pricePerWeek !== undefined &&
                          Number(item.pricePerWeek) > 0 && (
                            <div className="mb-2">
                              <h4>
                                ${Math.floor(Number(item.pricePerWeek))}/Week
                              </h4>
                            </div>
                          )}
                        {item.pricePerMonth !== undefined &&
                          Number(item.pricePerMonth) > 0 && (
                            <div className="mb-2">
                              <h4>
                                ${Math.floor(Number(item.pricePerMonth))}/Month
                              </h4>
                            </div>
                          )}
                      </>
                    );
                  })()}

                  {/* Rental Period Selection - Only show for non-owners */}
                  {!isOwner && item.isAvailable && (
                    <>
                      <hr />
                      {isAlreadyRenting && (
                        <div className="alert alert-warning py-2 mb-3" role="alert">
                          <i className="bi bi-exclamation-triangle-fill me-2"></i>
                          <small>You already have an active rental for this item</small>
                        </div>
                      )}
                      <div className="text-start">
                        {dateValidationError && (
                          <div
                            className="alert alert-danger py-2 mb-3"
                            role="alert"
                          >
                            <small>{dateValidationError}</small>
                          </div>
                        )}
                        <div className="mb-3">
                          <label className="form-label fw-medium mb-2">
                            Start
                          </label>
                          <div style={{ width: "60%" }}>
                            <DatePicker
                              selected={rentalDates.startDate}
                              onChange={(date: Date | null) =>
                                setRentalDates((prev) => ({
                                  ...prev,
                                  startDate: date,
                                }))
                              }
                              minDate={new Date()}
                              dateFormat="MM/dd/yyyy"
                              placeholderText="mm/dd/yyyy"
                              className="form-control mb-2 w-100"
                            />
                          </div>
                          <select
                            className="form-select"
                            style={{ width: "60%" }}
                            value={rentalDates.startTime}
                            onChange={(e) =>
                              setRentalDates((prev) => ({
                                ...prev,
                                startTime: e.target.value,
                              }))
                            }
                            disabled={!rentalDates.startDate}
                          >
                            <option value="">Pickup Time</option>
                            {generateTimeOptions(rentalDates.startDate).map(
                              (option) => (
                                <option key={option.value} value={option.value}>
                                  {option.label}
                                </option>
                              )
                            )}
                          </select>
                        </div>

                        <div className="mb-3">
                          <label className="form-label fw-medium mb-2">
                            End
                          </label>
                          <div style={{ width: "60%" }}>
                            <DatePicker
                              selected={rentalDates.endDate}
                              onChange={(date: Date | null) =>
                                setRentalDates((prev) => ({
                                  ...prev,
                                  endDate: date,
                                }))
                              }
                              minDate={rentalDates.startDate || new Date()}
                              dateFormat="MM/dd/yyyy"
                              placeholderText="mm/dd/yyyy"
                              className="form-control mb-2 w-100"
                            />
                          </div>
                          <select
                            className="form-select"
                            style={{ width: "60%" }}
                            value={rentalDates.endTime}
                            onChange={(e) =>
                              setRentalDates((prev) => ({
                                ...prev,
                                endTime: e.target.value,
                              }))
                            }
                            disabled={!rentalDates.endDate}
                          >
                            <option value="">Return Time</option>
                            {generateTimeOptions(rentalDates.endDate).map(
                              (option) => (
                                <option key={option.value} value={option.value}>
                                  {option.label}
                                </option>
                              )
                            )}
                          </select>
                        </div>

                        {rentalDates.startDate &&
                          rentalDates.startTime &&
                          rentalDates.endDate &&
                          rentalDates.endTime &&
                          !dateValidationError && (
                            <div className="mb-3 p-2 bg-light rounded text-center">
                              {costLoading ? (
                                <div
                                  className="spinner-border spinner-border-sm"
                                  role="status"
                                >
                                  <span className="visually-hidden">
                                    Calculating...
                                  </span>
                                </div>
                              ) : costError ? (
                                <small className="text-danger">
                                  {costError}
                                </small>
                              ) : totalCost > 0 ? (
                                <strong>Total: ${totalCost}</strong>
                              ) : null}
                            </div>
                          )}
                      </div>
                    </>
                  )}

                  {/* Action Buttons */}
                  {!isOwner && item.isAvailable && (
                    <div className="d-grid">
                      <button
                        className="btn btn-primary"
                        onClick={handleRent}
                        disabled={
                          !rentalDates.startDate ||
                          !rentalDates.startTime ||
                          !rentalDates.endDate ||
                          !rentalDates.endTime ||
                          !!dateValidationError
                        }
                      >
                        Rent Now
                      </button>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Confirmation Modal */}
      <ConfirmationModal
        show={showConfirmModal}
        onClose={handleCancelConfirm}
        onConfirm={handleConfirmAction}
        title={
          confirmAction === "delete" ? "Confirm Delete" : "Confirm Restore"
        }
        message={
          confirmAction === "delete"
            ? "Are you sure you want to delete this item? It will be hidden from public listings."
            : "Are you sure you want to restore this item? It will be visible to the public again."
        }
        confirmText={confirmAction === "delete" ? "Delete" : "Restore"}
        cancelText="Cancel"
        confirmButtonClass={
          confirmAction === "delete" ? "btn-danger" : "btn-success"
        }
        loading={deleteLoading}
        showReasonInput={confirmAction === "delete"}
        reason={deletionReason}
        onReasonChange={setDeletionReason}
        reasonPlaceholder="Enter reason for deletion (e.g., policy violation, inappropriate content)"
        reasonRequired={true}
      />

      {/* Mobile Sticky Bottom Bar */}
      {!isOwner && item.isAvailable && (
        <div className="mobile-sticky-bottom-bar d-md-none">
          <div className="d-flex align-items-center justify-content-between">
            <div className="price-display">
              {(() => {
                const prices = [
                  { value: Number(item.pricePerHour), label: "/hour" },
                  { value: Number(item.pricePerDay), label: "/day" },
                  { value: Number(item.pricePerWeek), label: "/week" },
                  { value: Number(item.pricePerMonth), label: "/month" },
                ].filter((p) => p.value > 0);

                if (prices.length === 0) {
                  return <span className="fw-bold">Free to Borrow</span>;
                }

                const lowestPrice = prices[0];
                return (
                  <span>
                    <span className="fw-bold fs-5">
                      ${Math.floor(lowestPrice.value)}
                    </span>
                    <span className="text-muted">{lowestPrice.label}</span>
                  </span>
                );
              })()}
            </div>
            <button
              className="btn btn-primary btn-lg"
              onClick={() => {
                const mobilePricingCard = document.getElementById("mobile-pricing-card");
                if (mobilePricingCard) {
                  mobilePricingCard.scrollIntoView({
                    behavior: "smooth",
                    block: "start",
                  });
                }
              }}
            >
              Check Availability
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default ItemDetail;
