import React, { useState, useEffect } from "react";
import { useParams, useNavigate, useSearchParams } from "react-router-dom";
import { Item } from "../types";
import { useAuth } from "../contexts/AuthContext";
import { itemAPI, rentalAPI } from "../services/api";
import { getImageUrl } from "../services/uploadService";
import EmbeddedStripeCheckout from "../components/EmbeddedStripeCheckout";
import VerificationCodeModal from "../components/VerificationCodeModal";

// Helper function to validate date selection
const validateDates = (
  startDateTime: Date | null,
  endDateTime: Date | null
): { isValid: boolean; error: string | null } => {
  if (!startDateTime || !endDateTime) {
    return { isValid: false, error: "Start and end date/time are required" };
  }

  const now = new Date();

  // Check if start datetime is in the past
  if (startDateTime < now) {
    return { isValid: false, error: "Start date/time cannot be in the past" };
  }

  // Check if end datetime is after start datetime
  if (endDateTime <= startDateTime) {
    return {
      isValid: false,
      error: "End date/time must be after start date/time",
    };
  }

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

// Helper to parse ISO string from URL params
const parseDateTime = (isoString: string | null): Date | null => {
  if (!isoString) return null;
  const date = new Date(isoString);
  return isNaN(date.getTime()) ? null : date;
};

const RentItem: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { user, checkAuth } = useAuth();
  const [searchParams] = useSearchParams();
  const [item, setItem] = useState<Item | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showVerificationModal, setShowVerificationModal] = useState(false);
  const [pendingSubmit, setPendingSubmit] = useState(false);

  const [formData, setFormData] = useState({
    intendedUse: "",
  });

  const [rentalDates, setRentalDates] = useState<{
    startDateTime: Date | null;
    endDateTime: Date | null;
  }>({
    startDateTime: parseDateTime(searchParams.get("startDateTime")),
    endDateTime: parseDateTime(searchParams.get("endDateTime")),
  });

  const [totalCost, setTotalCost] = useState(0);
  const [costLoading, setCostLoading] = useState(false);
  const [costError, setCostError] = useState<string | null>(null);
  const [completed, setCompleted] = useState(false);
  const [dateValidationError, setDateValidationError] = useState<string | null>(
    null
  );

  const formatDateTime = (date: Date | null) => {
    if (!date) return "";
    return date.toLocaleString("en-US", {
      month: "2-digit",
      day: "2-digit",
      year: "numeric",
      hour: "numeric",
      minute: "2-digit",
      hour12: true,
    });
  };

  const calculateTotalCost = async () => {
    if (!item || !rentalDates.startDateTime || !rentalDates.endDateTime) {
      setTotalCost(0);
      return;
    }

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

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

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

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

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

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

  const fetchItem = async () => {
    try {
      const response = await itemAPI.getItem(id!);
      setItem(response.data);

      // Check if item is available
      if (!response.data.isAvailable) {
        setError("This item is not available for rent");
      }

      // Check if user is trying to rent their own item
      if (response.data.ownerId === user?.id) {
        setError("You cannot rent your own item");
      }
    } catch (err: any) {
      setError(err.response?.data?.message || "Failed to fetch item");
    } finally {
      setLoading(false);
    }
  };

  const getRentalData = () => {
    if (!rentalDates.startDateTime || !rentalDates.endDateTime) {
      return null;
    }

    return {
      itemId: id,
      startDateTime: rentalDates.startDateTime.toISOString(),
      endDateTime: rentalDates.endDateTime.toISOString(),
      intendedUse: formData.intendedUse || undefined,
      totalAmount: totalCost,
    };
  };

  const handleFreeBorrow = async () => {
    const rentalData = getRentalData();
    if (!rentalData) return;

    try {
      setError(null);
      await rentalAPI.createRental(rentalData);
      setCompleted(true);
    } catch (error: any) {
      // Check for email verification required error
      if (
        error.response?.status === 403 &&
        error.response?.data?.code === "EMAIL_NOT_VERIFIED"
      ) {
        setPendingSubmit(true);
        setShowVerificationModal(true);
        return;
      }
      setError(
        error.response?.data?.error || "Failed to create rental request"
      );
    }
  };

  const handleVerificationSuccess = async () => {
    setShowVerificationModal(false);
    await checkAuth(); // Refresh user data
    if (pendingSubmit) {
      setPendingSubmit(false);
      // Retry the rental submission
      handleFreeBorrow();
    }
  };

  const handleChange = (
    e: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  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 (
    !item ||
    error === "You cannot rent your own item" ||
    error === "This item is not available for rent"
  ) {
    return (
      <div className="container mt-5">
        <div className="alert alert-danger" role="alert">
          {error || "Item not found"}
        </div>
        <button className="btn btn-secondary" onClick={() => navigate(-1)}>
          Go Back
        </button>
      </div>
    );
  }

  return (
    <div style={{ backgroundColor: "#F7F9FB", minHeight: "100vh" }}>
      <div className="container pt-5">
        <div className="row justify-content-center">
          <div className="col-md-10">
            <h1>Complete Your Request</h1>

            {/* Email Verification Warning Banner */}
            {user && !user.isVerified && (
              <div className="alert alert-warning d-flex align-items-center mb-4">
                <i className="bi bi-exclamation-triangle-fill me-2"></i>
                <div className="flex-grow-1">
                  <strong>Email verification required.</strong> Verify your
                  email to book rentals.
                </div>
                <button
                  className="btn btn-warning btn-sm ms-3"
                  onClick={() => setShowVerificationModal(true)}
                >
                  Verify Now
                </button>
              </div>
            )}

            {error && (
              <div className="alert alert-danger" role="alert">
                {error}
              </div>
            )}

            <div className="row">
              {/* Pricing Card - appears first on mobile, right side on desktop */}
              <div className="col-md-4 order-first order-md-last mb-4 mb-md-0">
                <div className="card">
                  <div className="card-body">
                    {item.imageFilenames && item.imageFilenames[0] && (
                      <img
                        src={getImageUrl(item.imageFilenames[0], "medium")}
                        alt={item.name}
                        className="img-fluid rounded mb-3"
                        onError={(e) => {
                          const target = e.currentTarget;
                          if (!target.dataset.fallback) {
                            target.dataset.fallback = "true";
                            target.src = getImageUrl(
                              item.imageFilenames[0],
                              "original"
                            );
                          }
                        }}
                        style={{
                          width: "100%",
                          height: "150px",
                          objectFit: "contain",
                          backgroundColor: "#f8f9fa",
                        }}
                      />
                    )}

                    <h6>{item.name}</h6>
                    <p className="text-muted small">
                      {item.city && item.state
                        ? `${item.city}, ${item.state}`
                        : ""}
                    </p>

                    <hr />

                    {/* Pricing */}
                    <div className="mb-3 text-center">
                      {totalCost === 0 ? (
                        <h6>Free to Borrow</h6>
                      ) : (
                        <>
                          {item.pricePerHour &&
                            Number(item.pricePerHour) > 0 && (
                              <h6>
                                ${Math.floor(Number(item.pricePerHour))}/Hour
                              </h6>
                            )}
                          {item.pricePerDay && Number(item.pricePerDay) > 0 && (
                            <h6>${Math.floor(Number(item.pricePerDay))}/Day</h6>
                          )}
                        </>
                      )}
                    </div>

                    {/* Selected Dates */}
                    {rentalDates.startDateTime && rentalDates.endDateTime && (
                      <div className="mb-3">
                        <div className="small mb-1">
                          <strong>Check-in:</strong>{" "}
                          {formatDateTime(rentalDates.startDateTime)}
                        </div>
                        <div className="small">
                          <strong>Check-out:</strong>{" "}
                          {formatDateTime(rentalDates.endDateTime)}
                        </div>
                      </div>
                    )}

                    {/* Total Cost */}
                    <>
                      <hr />
                      <div className="d-flex justify-content-between">
                        <strong>Total:</strong>
                        {costLoading ? (
                          <div
                            className="spinner-border spinner-border-sm"
                            role="status"
                          >
                            <span className="visually-hidden">
                              Calculating...
                            </span>
                          </div>
                        ) : costError ? (
                          <small className="text-danger">Error</small>
                        ) : totalCost > 0 ? (
                          <strong>${totalCost}</strong>
                        ) : (
                          <strong>$0</strong>
                        )}
                      </div>
                    </>
                  </div>
                </div>
              </div>

              {/* Form - appears second on mobile, left side on desktop */}
              <div className="col-md-8">
                {completed ? (
                  <div className="mb-4">
                    <div className="text-center">
                      <div className="alert alert-success">
                        <i className="bi bi-check-circle-fill display-1 text-success mb-3"></i>
                        <h3>Rental Request Sent!</h3>
                        <p className="mb-3">
                          Your rental request has been submitted to the owner.
                          You'll only be charged if they approve your request.
                        </p>
                        <div className="d-grid gap-2 d-md-block">
                          <button
                            className="btn btn-primary me-2"
                            onClick={() => navigate("/renting")}
                          >
                            View My Rentals
                          </button>
                          <button
                            className="btn btn-outline-secondary"
                            onClick={() => navigate("/")}
                          >
                            Continue Browsing
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                ) : (
                  <div className="mb-4">
                    <div>
                      <div className="card mb-3">
                        <div className="card-body">
                          <h6 className="mb-3">
                            What will you use this for?{" "}
                            <span className="text-muted">(Optional)</span>
                          </h6>
                          <textarea
                            id="intendedUse"
                            name="intendedUse"
                            className="form-control"
                            rows={3}
                            value={formData.intendedUse}
                            onChange={handleChange}
                            placeholder="Let the owner know how you plan to use their item..."
                            maxLength={500}
                          />
                          <div className="form-text">
                            {formData.intendedUse.length}/500 characters
                          </div>
                        </div>
                      </div>

                      {dateValidationError ? (
                        <div className="alert alert-danger">
                          <i className="bi bi-exclamation-triangle me-2"></i>
                          {dateValidationError}
                        </div>
                      ) : costError ? (
                        <div className="alert alert-danger">
                          <i className="bi bi-exclamation-triangle me-2"></i>
                          {costError}
                          <div className="mt-2">
                            <button
                              type="button"
                              className="btn btn-outline-secondary btn-sm"
                              onClick={() => navigate(`/items/${id}`)}
                            >
                              Choose Different Dates
                            </button>
                          </div>
                        </div>
                      ) : !rentalDates.startDateTime ||
                        !rentalDates.endDateTime ||
                        !getRentalData() ? (
                        <div className="alert alert-info">
                          <i className="bi bi-info-circle me-2"></i>
                          Please complete the rental dates and details above to
                          proceed with{" "}
                          {totalCost === 0
                            ? "your borrow request"
                            : "payment setup"}
                          .
                        </div>
                      ) : totalCost === 0 ? (
                        <>
                          <div className="d-grid gap-2">
                            <button
                              type="button"
                              className="btn btn-primary"
                              onClick={handleFreeBorrow}
                            >
                              Confirm Borrow Request
                            </button>
                            <button
                              type="button"
                              className="btn btn-outline-secondary"
                              onClick={() => navigate(`/items/${id}`)}
                            >
                              Cancel Request
                            </button>
                          </div>
                        </>
                      ) : (
                        <>
                          <div className="card mb-3">
                            <div className="card-body">
                              <p className="mb-0">
                                Add your payment method to complete your
                                request. You'll only be charged if the owner
                                approves your request.
                              </p>
                            </div>
                          </div>

                          <EmbeddedStripeCheckout
                            rentalData={getRentalData()}
                            onSuccess={() => setCompleted(true)}
                            onError={(error) => setError(error)}
                          />

                          <div className="text-center mt-3">
                            <button
                              type="button"
                              className="btn btn-outline-secondary"
                              onClick={() => navigate(`/items/${id}`)}
                            >
                              Cancel Request
                            </button>
                          </div>
                        </>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Email Verification Modal */}
        {user && (
          <VerificationCodeModal
            show={showVerificationModal}
            onHide={() => {
              setShowVerificationModal(false);
              setPendingSubmit(false);
            }}
            email={user.email || ""}
            onVerified={handleVerificationSuccess}
          />
        )}
      </div>
    </div>
  );
};

export default RentItem;
