import React, { useState } from 'react';
import { 
  SOCIAL_POSTS, 
  PUBLIC_MIXER_EVENTS, 
  STORY_REELS 
} from '../data/socialData';
import { InstagramFeedPlugin } from './InstagramFeedPlugin';
import { 
  Heart, 
  MessageCircle, 
  Share2, 
  Sparkles, 
  Ticket, 
  Instagram, 
  MapPin, 
  Calendar, 
  Clock, 
  Music, 
  Camera, 
  CheckCircle2, 
  Users,
  Send,
  Plus
} from 'lucide-react';
import confetti from 'canvas-confetti';

interface SocialClubProps {
  onOpenStory: (storyId: string) => void;
  onBookMixerTicket: (event: any) => void;
  onOpenSplitModal: () => void;
}

export const SocialClub: React.FC<SocialClubProps> = ({
  onOpenStory,
  onBookMixerTicket,
  onOpenSplitModal
}) => {
  const [posts, setPosts] = useState(SOCIAL_POSTS);
  const [likedPosts, setLikedPosts] = useState<Record<string, boolean>>({});
  const [commentOpenPostId, setCommentOpenPostId] = useState<string | null>(null);
  const [newCommentText, setNewCommentText] = useState('');
  const [commentsMap, setCommentsMap] = useState<Record<string, string[]>>({
    'post-1': ['Such an unforgettable sunset! 🥂✨', 'The champagne flutes and foredeck banquettes are top notch!'],
    'post-2': ['That illuminated marble bar is magnificent.', 'Best corporate executive cruise in HK.'],
    'post-3': ['The 10-seater teak table was incredible! 🌊', 'Count us in for our next celebration!'],
    'post-4': ['That flybridge canopy shade was a lifesaver in Sai Kung. 🎧☀️']
  });

  const [showUploadModal, setShowUploadModal] = useState(false);
  const [uploadUsername, setUploadUsername] = useState('');
  const [uploadCaption, setUploadCaption] = useState('');
  const [uploadLocation, setUploadLocation] = useState('Victoria Harbour, Central');

  const toggleLike = (postId: string) => {
    setLikedPosts(prev => {
      const isLiked = !!prev[postId];
      const nextState = !isLiked;
      
      setPosts(currentPosts => 
        currentPosts.map(p => 
          p.id === postId 
            ? { ...p, likes: p.likes + (nextState ? 1 : -1) }
            : p
        )
      );

      if (nextState) {
        try {
          confetti({
            particleCount: 25,
            spread: 45,
            origin: { y: 0.7 }
          });
        } catch (e) {}
      }

      return { ...prev, [postId]: nextState };
    });
  };

  const handleAddComment = (postId: string) => {
    if (!newCommentText.trim()) return;
    setCommentsMap(prev => ({
      ...prev,
      [postId]: [...(prev[postId] || []), newCommentText.trim()]
    }));
    setPosts(prev => prev.map(p => p.id === postId ? { ...p, commentsCount: p.commentsCount + 1 } : p));
    setNewCommentText('');
  };

  const handleGuestSubmitPhoto = (e: React.FormEvent) => {
    e.preventDefault();
    if (!uploadUsername || !uploadCaption) return;

    const newPost = {
      id: `user-post-${Date.now()}`,
      username: uploadUsername.toLowerCase().replace(/\s+/g, '_'),
      handle: `@${uploadUsername.toLowerCase().replace(/\s+/g, '')}`,
      avatar: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&w=200&q=80',
      image: '/images/yacht/bowloungeoverview.jpg',
      caption: `${uploadCaption} 🛥️✨ #EntourageHK`,
      likes: 1,
      commentsCount: 0,
      location: uploadLocation,
      timestamp: 'Just now',
      tags: ['#EntourageHK', '#YachtLife', '#HongKong'],
      charterType: 'Guest Moment'
    };

    setPosts([newPost, ...posts]);
    setShowUploadModal(false);
    setUploadUsername('');
    setUploadCaption('');

    try {
      confetti({
        particleCount: 50,
        spread: 60,
        origin: { y: 0.6 }
      });
    } catch (e) {}
  };

  return (
    <section id="social" className="py-24 bg-[#080d17] relative overflow-hidden border-t border-white/5">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
        
        {/* Section Header */}
        <div className="flex flex-col md:flex-row md:items-end justify-between mb-12 gap-6">
          <div>
            <a
              href="https://www.instagram.com/entourage.hk"
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-2.5 px-4 py-2 rounded-full bg-gradient-to-r from-purple-900/40 via-pink-900/40 to-amber-900/40 hover:from-purple-800/60 hover:to-amber-800/60 border border-pink-500/30 hover:border-pink-400 text-white text-sm sm:text-base font-bold tracking-wide mb-4 font-mono transition-all group shadow-md"
            >
              <div className="p-1 rounded-full bg-gradient-to-tr from-purple-500 via-pink-500 to-amber-400 text-white">
                <Instagram className="w-4 h-4" />
              </div>
              <span className="text-amber-300 group-hover:text-white transition-colors">@entourage.hk on Instagram</span>
              <span className="text-xs px-2 py-0.5 rounded-full bg-pink-500/20 text-pink-300 font-sans font-bold">14.8K+</span>
            </a>
            <h2 className="text-3xl sm:text-4xl lg:text-5xl font-extrabold text-white tracking-tight">
              Moments Aboard <span className="text-amber-400 font-serif-luxury font-normal">Entourage</span>
            </h2>
            <p className="text-slate-400 text-base mt-2 max-w-2xl font-light leading-relaxed">
              Discover real moments captured by charter guests. Follow{' '}
              <a 
                href="https://www.instagram.com/entourage.hk" 
                target="_blank" 
                rel="noopener noreferrer" 
                className="text-amber-400 font-bold hover:underline inline-flex items-center gap-0.5"
              >
                @entourage.hk
              </a>{' '}
              and tag <span className="text-white font-semibold">#EntourageHK</span> to join our curated feed.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-3">
            <a
              href="https://www.instagram.com/entourage.hk"
              target="_blank"
              rel="noopener noreferrer"
              className="px-6 py-3 rounded-xl bg-gradient-to-r from-purple-600 via-pink-600 to-amber-500 hover:from-purple-500 hover:to-amber-400 text-white text-sm font-black transition-all shadow-lg shadow-pink-500/25 hover:scale-105 flex items-center gap-2.5 border border-white/20"
            >
              <Instagram className="w-5 h-5 text-white" />
              <span>Follow @entourage.hk</span>
            </a>

            <button
              id="btn-upload-guest-photo"
              onClick={() => setShowUploadModal(true)}
              className="px-4 py-3 rounded-xl bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold border border-white/15 transition-all flex items-center gap-2"
            >
              <Camera className="w-4 h-4 text-amber-400" />
              <span>Share A Photo</span>
            </button>

            <button
              onClick={onOpenSplitModal}
              className="px-4 py-3 rounded-xl bg-sky-500/10 hover:bg-sky-500/20 text-sky-300 text-xs font-bold border border-sky-500/30 transition-all flex items-center gap-2"
            >
              <Users className="w-4 h-4 text-sky-400" />
              <span>Split Charter Cost</span>
            </button>
          </div>
        </div>

        {/* Live Instagram Feed Plugin - Last 6 Images of @entourage.hk */}
        <InstagramFeedPlugin />

        {/* Live Stories Horizontal Scroll Bar with Real Photos */}
        <div className="mb-14 p-5 rounded-3xl bg-slate-900 border border-white/10">
          <div className="flex items-center gap-2 mb-3.5 px-1">
            <span className="text-xs font-bold uppercase tracking-wider text-slate-300 font-mono">
              Featured Vessel Spaces & Live Stories
            </span>
          </div>

          <div className="flex items-center gap-4 sm:gap-6 overflow-x-auto pb-2 scrollbar-none">
            {STORY_REELS.map((story) => (
              <button
                key={story.id}
                onClick={() => onOpenStory(story.id)}
                className="flex flex-col items-center gap-2 group shrink-0 focus:outline-none"
              >
                <div className="relative p-1 rounded-full border-2 border-amber-400/60 group-hover:border-amber-400 transition-colors">
                  <div className="w-16 h-16 sm:w-20 sm:h-20 rounded-full overflow-hidden bg-slate-950">
                    <img
                      src={story.previewImage}
                      alt={story.user}
                      className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
                    />
                  </div>
                </div>
                <span className="text-[11px] font-medium text-slate-300 group-hover:text-amber-300 transition-colors max-w-[80px] sm:max-w-[95px] truncate text-center">
                  {story.user}
                </span>
              </button>
            ))}
          </div>
        </div>

        {/* Social Feed Grid with Authentic Yacht Photos */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-20">
          {posts.map((post) => {
            const isLiked = !!likedPosts[post.id];
            const postComments = commentsMap[post.id] || [];
            const isCommentsOpen = commentOpenPostId === post.id;

            return (
              <div
                key={post.id}
                className="rounded-3xl overflow-hidden border border-white/10 bg-slate-900 shadow-xl flex flex-col justify-between"
              >
                {/* User Header */}
                <div className="p-4 flex items-center justify-between border-b border-white/5">
                  <div className="flex items-center gap-2.5">
                    <img
                      src={post.avatar}
                      alt={post.username}
                      className="w-8 h-8 rounded-full object-cover border border-amber-400/30"
                    />
                    <div>
                      <div className="text-xs font-bold text-white flex items-center gap-1">
                        <span>{post.handle}</span>
                        <CheckCircle2 className="w-3 h-3 text-sky-400" />
                      </div>
                      <div className="text-[10px] text-slate-400 flex items-center gap-1">
                        <MapPin className="w-3 h-3 text-amber-400" />
                        <span className="truncate max-w-[120px]">{post.location}</span>
                      </div>
                    </div>
                  </div>

                  <span className="text-[10px] text-slate-400 font-mono">
                    {post.timestamp}
                  </span>
                </div>

                {/* Photo */}
                <div className="relative h-64 overflow-hidden bg-slate-950 group">
                  <img
                    src={post.image}
                    alt={post.caption}
                    className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105 filter brightness-95"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-slate-950/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-end p-4">
                    <span className="text-[10px] font-mono text-amber-300 bg-slate-950/90 px-2.5 py-1 rounded-full border border-white/10">
                      {post.charterType}
                    </span>
                  </div>
                </div>

                {/* Post Actions & Caption */}
                <div className="p-4 flex-1 flex flex-col justify-between space-y-3">
                  <div>
                    {/* Action buttons */}
                    <div className="flex items-center justify-between mb-2">
                      <div className="flex items-center gap-3">
                        <button
                          onClick={() => toggleLike(post.id)}
                          className={`flex items-center gap-1.5 text-xs font-semibold transition-colors ${
                            isLiked ? 'text-rose-500' : 'text-slate-300 hover:text-rose-400'
                          }`}
                        >
                          <Heart className={`w-4 h-4 ${isLiked ? 'fill-rose-500' : ''}`} />
                          <span className="font-mono">{post.likes}</span>
                        </button>

                        <button
                          onClick={() => setCommentOpenPostId(isCommentsOpen ? null : post.id)}
                          className="flex items-center gap-1.5 text-xs font-semibold text-slate-300 hover:text-sky-400 transition-colors"
                        >
                          <MessageCircle className="w-4 h-4" />
                          <span className="font-mono">{post.commentsCount}</span>
                        </button>
                      </div>

                      <button
                        onClick={onOpenSplitModal}
                        className="text-slate-400 hover:text-amber-400 transition-colors"
                        title="Share yacht charter idea"
                      >
                        <Share2 className="w-4 h-4" />
                      </button>
                    </div>

                    <p className="text-xs text-slate-300 leading-relaxed line-clamp-3 font-light">
                      <span className="font-bold text-white mr-1.5">{post.handle}</span>
                      {post.caption}
                    </p>
                  </div>

                  {/* Inline Comments Section */}
                  {isCommentsOpen && (
                    <div className="pt-3 border-t border-white/10 space-y-2">
                      <div className="max-h-24 overflow-y-auto space-y-1 pr-1">
                        {postComments.map((c, i) => (
                          <div key={i} className="text-[11px] text-slate-300 bg-slate-950 p-1.5 rounded-lg border border-white/5">
                            <span className="font-bold text-amber-300 mr-1">guest:</span> {c}
                          </div>
                        ))}
                      </div>

                      <div className="flex gap-1">
                        <input
                          type="text"
                          value={newCommentText}
                          onChange={(e) => setNewCommentText(e.target.value)}
                          onKeyDown={(e) => e.key === 'Enter' && handleAddComment(post.id)}
                          placeholder="Add comment..."
                          className="flex-1 bg-slate-950 border border-white/15 rounded-lg px-2 py-1 text-xs text-white focus:outline-none focus:border-amber-400"
                        />
                        <button
                          onClick={() => handleAddComment(post.id)}
                          className="px-2.5 py-1 rounded-lg bg-amber-400 text-slate-950 text-xs font-bold hover:bg-amber-300"
                        >
                          <Send className="w-3 h-3" />
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        {/* Public Mixer Events Showcase */}
        <div id="mixers" className="scroll-mt-24">
          <div className="text-center max-w-3xl mx-auto space-y-3 mb-12">
            <div className="inline-flex items-center gap-2 px-3.5 py-1 rounded-full bg-slate-900 border border-white/10 text-slate-300 text-xs font-semibold uppercase tracking-wider font-mono">
              <Ticket className="w-3.5 h-3.5 text-amber-400" />
              <span>Public Ticketed Social Mixers</span>
            </div>
            <h3 className="text-3xl sm:text-4xl font-extrabold text-white tracking-tight">
              Join a Curated <span className="text-amber-400 font-serif-luxury font-normal">Social Sail</span>
            </h3>
            <p className="text-slate-400 text-sm sm:text-base font-light leading-relaxed">
              Experience the 75ft Entourage superyacht with individual tickets. Meet fellow professionals, founders, and yacht enthusiasts with all drinks, food, and music included.
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {PUBLIC_MIXER_EVENTS.map((event) => {
              const spotsLeft = event.totalSpots - event.bookedSpots;
              return (
                <div
                  key={event.id}
                  className="rounded-3xl overflow-hidden border border-white/10 bg-slate-900 shadow-xl flex flex-col justify-between"
                >
                  <div className="relative h-48 overflow-hidden bg-slate-950">
                    <img
                      src={event.image}
                      alt={event.title}
                      className="w-full h-full object-cover transition-transform duration-500 hover:scale-105 filter brightness-90"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-slate-950 via-transparent to-transparent" />
                    
                    <span className="absolute top-3 left-3 px-3 py-1 rounded-full bg-slate-950/90 backdrop-blur-md border border-white/15 text-amber-400 text-[10px] font-mono uppercase tracking-wider font-bold">
                      {event.badge}
                    </span>

                    <div className="absolute bottom-3 left-3 right-3 flex items-center justify-between text-xs text-white">
                      <span className="flex items-center gap-1 font-semibold text-slate-200 bg-slate-950/80 px-2 py-0.5 rounded-md border border-white/10">
                        <Calendar className="w-3.5 h-3.5 text-amber-400" /> {event.date}
                      </span>
                      <span className="bg-slate-950/80 px-2 py-0.5 rounded-md text-[11px] text-slate-300 font-mono border border-white/10">
                        {event.time}
                      </span>
                    </div>
                  </div>

                  <div className="p-6 flex-1 flex flex-col justify-between space-y-4">
                    <div>
                      <h4 className="text-lg font-bold text-white mb-1">
                        {event.title}
                      </h4>
                      <p className="text-xs text-amber-400 font-medium mb-3">
                        {event.theme}
                      </p>

                      <div className="space-y-2 text-xs text-slate-300 mb-4">
                        <div className="flex items-center gap-2">
                          <MapPin className="w-3.5 h-3.5 text-amber-400 shrink-0" />
                          <span>Departing: {event.departure}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <Music className="w-3.5 h-3.5 text-purple-400 shrink-0" />
                          <span className="truncate">{event.djLineup}</span>
                        </div>
                      </div>

                      {/* Inclusions */}
                      <div className="space-y-1.5 pt-3 border-t border-white/10">
                        {event.includes.map((inc, i) => (
                          <div key={i} className="flex items-start gap-2 text-[11px] text-slate-300 font-light">
                            <CheckCircle2 className="w-3 h-3 text-emerald-400 shrink-0 mt-0.5" />
                            <span>{inc}</span>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* Ticket Price & Booking Button */}
                    <div className="pt-4 border-t border-white/10">
                      <div className="flex items-baseline justify-between mb-3">
                        <div>
                          <span className="text-[10px] text-slate-400 uppercase block font-mono">All-Inclusive Pass</span>
                          <div className="text-2xl font-bold text-white font-mono">
                            HK$ {event.pricePerTicketHKD.toLocaleString()}
                          </div>
                        </div>
                        <span className="text-[11px] font-bold text-emerald-400 font-mono bg-emerald-500/10 px-2.5 py-1 rounded-lg border border-emerald-500/20">
                          {spotsLeft} Spots Left
                        </span>
                      </div>

                      <button
                        onClick={() => onBookMixerTicket(event)}
                        className="w-full py-3 rounded-xl bg-amber-400 hover:bg-amber-300 text-slate-950 font-bold text-xs uppercase tracking-wider transition-all flex items-center justify-center gap-2"
                      >
                        <Ticket className="w-4 h-4 text-slate-950" />
                        <span>Reserve Mixer Ticket</span>
                      </button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

      </div>

      {/* Guest Photo Upload Modal */}
      {showUploadModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-md">
          <div className="bg-slate-900 border border-white/15 rounded-3xl max-w-md w-full p-6 shadow-2xl space-y-4">
            <div className="flex items-center justify-between border-b border-white/10 pb-3">
              <h3 className="text-base font-bold text-white flex items-center gap-2">
                <Camera className="w-4 h-4 text-amber-400" />
                <span>Share Your Entourage Moment</span>
              </h3>
              <button 
                onClick={() => setShowUploadModal(false)}
                className="text-slate-400 hover:text-white text-sm"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleGuestSubmitPhoto} className="space-y-3">
              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Your Name / Instagram Handle</label>
                <input
                  type="text"
                  required
                  value={uploadUsername}
                  onChange={(e) => setUploadUsername(e.target.value)}
                  placeholder="@sarah_in_hk or Sarah W."
                  className="w-full bg-slate-950 border border-white/15 rounded-xl p-2.5 text-xs text-white focus:outline-none focus:border-amber-400 font-mono"
                />
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Location of Charter</label>
                <select
                  value={uploadLocation}
                  onChange={(e) => setUploadLocation(e.target.value)}
                  className="w-full bg-slate-950 border border-white/15 rounded-xl p-2.5 text-xs text-white focus:outline-none focus:border-amber-400"
                >
                  <option value="Victoria Harbour, Central Pier 9">Victoria Harbour, Central Pier 9</option>
                  <option value="Tai Long Wan, Sai Kung">Tai Long Wan, Sai Kung</option>
                  <option value="Deep Water Bay, Southside">Deep Water Bay, Southside</option>
                  <option value="Repulse Bay Beach">Repulse Bay Beach</option>
                  <option value="Po Toi Island">Po Toi Island</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Caption & Memory</label>
                <textarea
                  required
                  value={uploadCaption}
                  onChange={(e) => setUploadCaption(e.target.value)}
                  placeholder="Describe your charter experience..."
                  className="w-full bg-slate-950 border border-white/15 rounded-xl p-2.5 text-xs text-white focus:outline-none focus:border-amber-400 h-20"
                />
              </div>

              <button
                type="submit"
                className="w-full py-3 rounded-xl bg-amber-400 hover:bg-amber-300 text-slate-950 font-bold text-xs uppercase tracking-wider"
              >
                Post to Entourage Board
              </button>
            </form>
          </div>
        </div>
      )}

    </section>
  );
};
