import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Heart, MapPin, Eye, Star, MessageSquare, Share2, Flag, ChevronLeft, ChevronRight } from 'lucide-react';
import { Card } from '../components/ui/Card';
import { Button } from '../components/ui/Button';
import { Badge } from '../components/ui/Badge';
import { Avatar } from '../components/ui/Avatar';
import { AvailabilityCalendar } from '../components/rentals/AvailabilityCalendar';
import { BookingForm } from '../components/rentals/BookingForm';
import { ReviewCard } from '../components/rentals/ReviewCard';
import { PriceDisplay } from '../components/rentals/PriceDisplay';
import { api } from '../api/client';
import { useAuth } from '../context/AuthContext';
import { formatDate } from '../utils/format';
import type { RentalListing, RentalReview } from '../types/rental';

export function RentalDetailPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user, isAuthenticated } = useAuth();
  const [rental, setRental] = useState<RentalListing | null>(null);
  const [reviews, setReviews] = useState<RentalReview[]>([]);
  const [blockedDates, setBlockedDates] = useState<Array<{ start: string; end: string }>>([]);
  const [bookedDates, setBookedDates] = useState<Array<{ start: string; end: string }>>([]);
  const [loading, setLoading] = useState(true);
  const [isFav, setIsFav] = useState(false);
  const [activeImage, setActiveImage] = useState(0);

  useEffect(() => {
    if (!id) return;

    api.get<RentalListing>(`/rentals/${id}`)
      .then(data => {
        setRental(data);
        setIsFav(data.isFavorited ?? false);
        setReviews(data.reviews ?? []);
      })
      .catch(() => setRental(null))
      .finally(() => setLoading(false));

    api.get<{ blocks: Array<{ startDate: string; endDate: string; isBlocked: boolean }>; bookings: Array<{ startDate: string; endDate: string }> }>(`/rentals/${id}/availability`)
      .then(data => {
        setBlockedDates(data.blocks.filter(b => b.isBlocked).map(b => ({ start: b.startDate, end: b.endDate })));
        setBookedDates(data.bookings.map(b => ({ start: b.startDate, end: b.endDate })));
      })
      .catch(() => {});
  }, [id]);

  const handleFavorite = async () => {
    if (!rental || !isAuthenticated) return;
    try {
      const res = await api.post<{ isFavorited: boolean }>(`/rentals/${rental.id}/favorite`);
      setIsFav(res.isFavorited);
    } catch {}
  };

  const handleMessage = async () => {
    if (!rental || !isAuthenticated) return;
    try {
      const conversation = await api.post<{ id: string }>('/chat/conversations', {
        recipientId: rental.landlord.id,
        rentalListingId: rental.id,
      });
      navigate('/dashboard/messages', { state: { conversationId: conversation.id } });
    } catch {}
  };

  if (loading) return <div className="max-w-7xl mx-auto px-4 py-12 text-center text-gray-500">Loading...</div>;
  if (!rental) return <div className="max-w-7xl mx-auto px-4 py-12 text-center text-gray-500">Rental not found</div>;

  const isOwner = user?.id === rental.landlordId;
  const hasImages = rental.images && rental.images.length > 0;
  const cancellationLabel = rental.cancellationPolicy === 'FLEXIBLE' ? 'Free cancellation up to 24h before'
    : rental.cancellationPolicy === 'MODERATE' ? 'Free cancellation up to 5 days before'
    : 'No refund after booking confirmation';

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 py-8">
      {/* Image Gallery */}
      <div className="mb-8">
        <div className="relative aspect-[16/9] md:aspect-[2/1] bg-gradient-to-br from-primary-50 to-pink-50 rounded-2xl overflow-hidden mb-3">
          {hasImages ? (
            <img src={rental.images[activeImage]?.url} alt={rental.title} className="w-full h-full object-cover" />
          ) : (
            <div className="w-full h-full flex items-center justify-center">
              <span className="text-8xl">
                {rental.category === 'APARTMENT' ? '\uD83C\uDFE2' : rental.category === 'HOUSE' ? '\uD83C\uDFE0' : rental.category === 'CAR' ? '\uD83D\uDE97' : '\uD83D\uDEB2'}
              </span>
            </div>
          )}
          {hasImages && rental.images.length > 1 && (
            <>
              <button
                onClick={() => setActiveImage(prev => prev > 0 ? prev - 1 : rental.images.length - 1)}
                className="absolute left-3 top-1/2 -translate-y-1/2 w-9 h-9 bg-white/80 backdrop-blur rounded-full flex items-center justify-center hover:bg-white transition-colors cursor-pointer"
              >
                <ChevronLeft className="w-5 h-5 text-gray-700" />
              </button>
              <button
                onClick={() => setActiveImage(prev => prev < rental.images.length - 1 ? prev + 1 : 0)}
                className="absolute right-3 top-1/2 -translate-y-1/2 w-9 h-9 bg-white/80 backdrop-blur rounded-full flex items-center justify-center hover:bg-white transition-colors cursor-pointer"
              >
                <ChevronRight className="w-5 h-5 text-gray-700" />
              </button>
            </>
          )}
        </div>
        {hasImages && rental.images.length > 1 && (
          <div className="grid grid-cols-5 sm:grid-cols-6 gap-2">
            {rental.images.slice(0, 6).map((img, i) => (
              <button
                key={img.id}
                onClick={() => setActiveImage(i)}
                className={`aspect-square rounded-xl overflow-hidden cursor-pointer transition-all ${
                  i === activeImage ? 'ring-2 ring-primary-400' : 'hover:ring-2 hover:ring-gray-300'
                }`}
              >
                <img src={img.url} alt="" className="w-full h-full object-cover" />
              </button>
            ))}
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Left column - Details */}
        <div className="lg:col-span-2 space-y-6">
          {/* Title and meta */}
          <div>
            <div className="flex items-start justify-between">
              <div>
                <h1 className="text-2xl font-bold text-gray-900">{rental.title}</h1>
                <div className="flex items-center gap-3 mt-2">
                  <Badge variant="default" size="md">{rental.category.replace('_', ' ')}</Badge>
                  <span className="flex items-center gap-1 text-sm text-gray-400">
                    <MapPin className="w-4 h-4" /> {rental.location}
                  </span>
                  <span className="flex items-center gap-1 text-sm text-gray-400">
                    <Eye className="w-4 h-4" /> {rental.viewCount} views
                  </span>
                </div>
              </div>
              <div className="flex items-center gap-1">
                <button onClick={handleFavorite} className="p-2 rounded-xl hover:bg-gray-100 transition-colors cursor-pointer">
                  <Heart className={`w-6 h-6 ${isFav ? 'fill-pink-500 text-pink-500' : 'text-gray-400'}`} />
                </button>
              </div>
            </div>

            <div className="mt-4">
              <PriceDisplay
                dailyPrice={rental.dailyPrice ?? undefined}
                monthlyPrice={rental.monthlyPrice ?? undefined}
              />
            </div>
          </div>

          {/* Description */}
          <Card>
            <h3 className="font-semibold text-gray-900 mb-3">Description</h3>
            <p className="text-sm text-gray-600 leading-relaxed whitespace-pre-wrap">{rental.description}</p>
          </Card>

          {/* Amenities */}
          {rental.amenities.length > 0 && (
            <Card>
              <h3 className="font-semibold text-gray-900 mb-3">Amenities</h3>
              <div className="flex flex-wrap gap-2">
                {rental.amenities.map((amenity, i) => (
                  <span key={i} className="px-3 py-1.5 rounded-lg bg-primary-50 text-primary-700 text-sm font-medium">
                    {amenity}
                  </span>
                ))}
              </div>
            </Card>
          )}

          {/* Rules */}
          {rental.rules.length > 0 && (
            <Card>
              <h3 className="font-semibold text-gray-900 mb-3">House Rules</h3>
              <ul className="space-y-2">
                {rental.rules.map((rule, i) => (
                  <li key={i} className="flex items-start gap-2 text-sm text-gray-600">
                    <span className="text-gray-400 mt-0.5">--</span>
                    {rule}
                  </li>
                ))}
              </ul>
            </Card>
          )}

          {/* Cancellation Policy */}
          <Card>
            <h3 className="font-semibold text-gray-900 mb-2">Cancellation Policy</h3>
            <Badge variant={rental.cancellationPolicy === 'FLEXIBLE' ? 'success' : rental.cancellationPolicy === 'MODERATE' ? 'warning' : 'error'} size="md">
              {rental.cancellationPolicy}
            </Badge>
            <p className="text-sm text-gray-500 mt-2">{cancellationLabel}</p>
          </Card>

          {/* Availability Calendar */}
          <Card>
            <h3 className="font-semibold text-gray-900 mb-3">Availability</h3>
            <AvailabilityCalendar blockedDates={blockedDates} bookedDates={bookedDates} />
          </Card>

          {/* Reviews */}
          <div>
            <div className="flex items-center gap-2 mb-4">
              <h3 className="font-semibold text-gray-900">Reviews</h3>
              {rental.avgRating !== undefined && (
                <span className="flex items-center gap-1 text-sm font-medium">
                  <Star className="w-4 h-4 text-yellow-400 fill-yellow-400" />
                  {rental.avgRating.toFixed(1)}
                  {rental._count?.reviews !== undefined && (
                    <span className="text-gray-400">({rental._count.reviews})</span>
                  )}
                </span>
              )}
            </div>
            {reviews.length === 0 ? (
              <p className="text-sm text-gray-400">No reviews yet.</p>
            ) : (
              <div className="space-y-4">
                {reviews.map(review => (
                  <ReviewCard key={review.id} review={review} />
                ))}
              </div>
            )}
          </div>

          {/* Actions */}
          <div className="flex gap-4 text-sm text-gray-400">
            <button
              onClick={() => { navigator.clipboard.writeText(window.location.href); alert('Link copied to clipboard!'); }}
              className="flex items-center gap-1 hover:text-gray-600 cursor-pointer"
            >
              <Share2 className="w-4 h-4" /> Share
            </button>
            <button className="flex items-center gap-1 hover:text-gray-600 cursor-pointer">
              <Flag className="w-4 h-4" /> Report
            </button>
          </div>
        </div>

        {/* Right column - Booking and Landlord */}
        <div className="space-y-6">
          {/* Booking form */}
          {!isOwner && (
            <div className="sticky top-24 space-y-6">
              <Card padding="lg">
                <BookingForm rental={rental} />
              </Card>

              <Button variant="outline" className="w-full" onClick={handleMessage}>
                <MessageSquare className="w-4 h-4 mr-2" /> Message Landlord
              </Button>
            </div>
          )}

          {/* Landlord card */}
          <Card>
            <h3 className="text-sm font-medium text-gray-500 mb-3">Hosted by</h3>
            <div className="flex items-center gap-4">
              <Avatar name={rental.landlord.fullName} src={rental.landlord.avatar} size="lg" />
              <div className="flex-1">
                <h3 className="font-semibold text-gray-900">{rental.landlord.fullName}</h3>
                <div className="flex items-center gap-2 mt-1">
                  {rental.landlord.rating !== undefined && (
                    <>
                      <Star className="w-4 h-4 text-yellow-400 fill-yellow-400" />
                      <span className="text-sm font-medium">{rental.landlord.rating}</span>
                    </>
                  )}
                  <span className="text-xs text-gray-400">Joined {formatDate(rental.landlord.createdAt)}</span>
                </div>
                {rental.landlord.landlordVerified && (
                  <span className="mt-1"><Badge variant="success" size="sm">Verified</Badge></span>
                )}
              </div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}
