import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useBookmarks } from '@/hooks/useBookmarks';
import { 
  Star,
  Phone,
  MapPin,
  Eye,
  Heart,
  ExternalLink,
  Trash,
  CheckCircle,
  ArrowUpRight
} from 'lucide-react';
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';

const Bookmarks = () => {
  const { user } = useAuth();
  const { 
    bookmarks, 
    loading, 
    error, 
    removeBookmark, 
    loadBookmarks,
    getBookmarksCount 
  } = useBookmarks();

  const handleRemoveBookmark = async (bookmarkId: string) => {
    const success = await removeBookmark(bookmarkId);
    if (success) {
      toast.success('Bookmark removed successfully');
    }
  };

  const renderStars = (rating: number) => {
    const stars = [];
    const fullStars = Math.floor(rating);
    
    for (let i = 0; i < fullStars; i++) {
      stars.push(
        <Star 
          key={i} 
          size={14} 
          className="text-primary fill-current" 
        />
      );
    }

    const remainingStars = 5 - fullStars;
    for (let i = 0; i < remainingStars; i++) {
      stars.push(
        <Star 
          key={`empty-${i}`} 
          size={14} 
          className="text-muted" 
        />
      );
    }

    return stars;
  };

  if (loading) {
    return (
      <div className="body-content">
        <div className="container-xxl">
          <div className="flex items-center justify-center min-h-96">
            <div className="text-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
              <p className="mt-4 text-muted-foreground">Loading bookmarks...</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="body-content">
        <div className="container-xxl">
          <div className="flex items-center justify-center min-h-96">
            <div className="text-center">
              <p className="text-destructive mb-4">{error}</p>
              <Button onClick={loadBookmarks}>Try Again</Button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="body-content">
      <div className="decoration blur-2"></div>
      <div className="decoration blur-3"></div>
      <div className="container-xxl">
        {/* Header Section */}
        <div className="flex items-end justify-between mb-4" data-aos="fade-down">
          <div className="col">
            <div className="section-header">
              <div className="font-caveat text-2xl font-bold text-primary capitalize text-center xl:text-left mb-2">
                Bookmarked
              </div>
              <h2 className="text-xl font-semibold mb-0 capitalize text-center xl:text-left">
                Bookmarked Listings
              </h2>
              <div className="text-base text-center xl:text-left mt-2">
                Discover exciting categories. 
                <span className="text-primary font-semibold"> Find what you're looking for.</span>
              </div>
            </div>
          </div>
          <div className="col-12 col-xl-auto">
            <Link 
              to="/explore" 
              className="flex items-center text-sm font-bold gap-2 justify-center xl:justify-end tracking-wide text-primary uppercase hover:underline"
            >
              See All
              <ArrowUpRight className="h-4 w-4" />
            </Link>
          </div>
        </div>

        {/* Bookmarks List */}
        {bookmarks.length === 0 ? (
          <div className="text-center py-12">
            <Heart className="h-16 w-16 text-muted-foreground mx-auto mb-4" />
            <h3 className="text-xl font-semibold mb-2">No bookmarks yet</h3>
            <p className="text-muted-foreground mb-4">
              Start exploring and save your favorite places to see them here.
            </p>
            <Link to="/explore">
              <Button>
                Explore Now
              </Button>
            </Link>
          </div>
        ) : (
          <div className="space-y-3">
            {bookmarks.map((bookmark) => (
              <div 
                key={bookmark.id} 
                className="border-0 bg-background card card-hover flex-fill overflow-hidden rounded-3 shadow-sm w-100 card-hover-bg hover:shadow-md transition-shadow"
              >
                <Link 
                  to={`/listing-details/${bookmark.id}`} 
                  className="stretched-link absolute inset-0 z-0"
                  aria-label={`View details for ${bookmark.title}`}
                />
                <div className="card-body p-0">
                  <div className="flex h-full">
                    {/* Image Section */}
                    <div className="lg:w-1/4 md:w-2/5 sm:w-1/3 xl:w-1/6 relative">
                      <div className="card-image-hover dark-overlay h-full overflow-hidden relative">
                        <img 
                          src={bookmark.image} 
                          alt={bookmark.title}
                          className="h-full w-full object-cover"
                          style={{ height: '200px' }}
                        />
                      </div>
                    </div>

                    {/* Content Section */}
                    <div className="lg:w-3/4 md:w-3/5 sm:w-2/3 xl:w-5/6 p-3 lg:p-4 md:p-3 sm:p-4">
                      <div className="flex flex-col h-full">
                        {/* Remove Bookmark Button */}
                        <div className="flex gap-2 absolute top-3 right-3 z-10">
                          <button
                            onClick={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              handleRemoveBookmark(bookmark.id);
                            }}
                            className="flex items-center bg-background/90 backdrop-blur-sm p-2 rounded-full text-destructive hover:bg-destructive hover:text-destructive-foreground transition-colors"
                            data-tooltip="Remove Bookmark"
                            aria-label="Remove from bookmarks"
                          >
                            <Trash className="h-4 w-4" />
                          </button>
                        </div>

                        {/* Rating */}
                        <div className="flex items-center flex-wrap gap-1 text-primary mb-2">
                          <div className="flex">
                            {renderStars(bookmark.rating)}
                          </div>
                          <span className="font-medium text-primary">
                            <span className="text-base font-semibold mr-1">
                              ({bookmark.rating})
                            </span>
                            {bookmark.reviewCount.toLocaleString()} reviews
                          </span>
                        </div>

                        {/* Title */}
                        <h4 className="text-lg font-semibold mb-0 flex items-center gap-2">
                          <span>{bookmark.title}</span>
                          {bookmark.isVerified && (
                            <CheckCircle className="h-5 w-5 text-success" />
                          )}
                        </h4>

                        {/* Address */}
                        <p className="mt-1 text-sm text-muted-foreground">
                          {bookmark.address}
                        </p>

                        {/* Category & Price */}
                        <div className="flex items-center gap-2 mb-2">
                          <Badge variant="secondary" className="text-xs">
                            {bookmark.category}
                          </Badge>
                          {bookmark.price && (
                            <Badge variant="outline" className="text-xs">
                              {bookmark.price}
                            </Badge>
                          )}
                          {bookmark.isFeatured && (
                            <Badge variant="default" className="text-xs">
                              Featured
                            </Badge>
                          )}
                        </div>

                        {/* Amenities */}
                        {bookmark.amenities && bookmark.amenities.length > 0 && (
                          <div className="flex flex-wrap gap-1 mb-3">
                            {bookmark.amenities.slice(0, 3).map((amenity, index) => (
                              <span 
                                key={index}
                                className="text-xs bg-muted text-muted-foreground px-2 py-1 rounded"
                              >
                                {amenity}
                              </span>
                            ))}
                            {bookmark.amenities.length > 3 && (
                              <span className="text-xs text-muted-foreground">
                                +{bookmark.amenities.length - 3} more
                              </span>
                            )}
                          </div>
                        )}

                        {/* Contact Actions */}
                        <div className="flex flex-wrap gap-3 lg:gap-2 xl:gap-3 mt-auto z-10">
                          <a 
                            href={`tel:${bookmark.phone}`}
                            onClick={(e) => e.stopPropagation()}
                            className="flex gap-2 items-center text-sm font-semibold hover:text-primary transition-colors"
                          >
                            <Phone className="h-4 w-4 text-muted-foreground" />
                            <span>{bookmark.phone}</span>
                          </a>
                          <button
                            onClick={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              // Open directions in Google Maps
                              const mapsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(bookmark.address)}`;
                              window.open(mapsUrl, '_blank');
                            }}
                            className="flex gap-2 items-center text-sm font-semibold hover:text-primary transition-colors"
                          >
                            <MapPin className="h-4 w-4 text-muted-foreground" />
                            <span>Directions</span>
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Load More / Footer */}
        {bookmarks.length > 0 && (
          <div className="text-center mt-8">
            <p className="text-sm text-muted-foreground mb-4">
              Showing {bookmarks.length} of {getBookmarksCount()} bookmarked items
            </p>
            <Link to="/explore">
              <Button variant="outline" size="lg">
                Explore More Places
              </Button>
            </Link>
          </div>
        )}
      </div>
    </div>
  );
};

export default Bookmarks;