import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { 
  Heart, 
  Calendar, 
  Music, 
  Sparkles,
  Plus,
  Camera,
  Star,
  Clock,
  Users,
  MessageCircle
} from 'lucide-react';
import { useStore } from '../store/useStore';
import { formatDate } from '../utils/cn';
import toast from 'react-hot-toast';

export const MemoryLanePage = () => {
  const { currentUser, partnerUser, memoryLane, addMemoryLaneItem } = useStore();
  const [showAddMemory, setShowAddMemory] = useState(false);
  const [newMemory, setNewMemory] = useState({
    title: '',
    description: '',
    type: 'milestone' as 'shared_track' | 'playlist_created' | 'milestone',
  });

  // Generate some sample memories based on user activity
  useEffect(() => {
    if (currentUser && partnerUser && memoryLane.length === 0) {
      const sampleMemories = [
        {
          id: '1',
          type: 'milestone' as const,
          title: 'First Musical Connection',
          description: `${currentUser.user?.display_name} and ${partnerUser.user?.display_name} discovered their shared love for music`,
          date: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7 days ago
          users: [currentUser.user?.id || '', partnerUser.user?.id || ''],
        },
        {
          id: '2',
          type: 'shared_track' as const,
          title: 'Shared Love for This Song',
          description: `Both of you have been listening to "${currentUser.recentlyPlayed?.[0]?.track.name || 'Your favorite track'}" recently`,
          track: currentUser.recentlyPlayed?.[0]?.track,
          date: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000), // 3 days ago
          users: [currentUser.user?.id || '', partnerUser.user?.id || ''],
        },
        {
          id: '3',
          type: 'playlist_created' as const,
          title: 'Our First Mixed Playlist',
          description: 'Created a beautiful blend of your musical tastes',
          date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000), // 1 day ago
          users: [currentUser.user?.id || '', partnerUser.user?.id || ''],
        },
      ];

      sampleMemories.forEach(memory => {
        addMemoryLaneItem(memory);
      });
    }
  }, [currentUser, partnerUser, memoryLane.length, addMemoryLaneItem]);

  const handleAddMemory = () => {
    if (!newMemory.title.trim() || !newMemory.description.trim()) {
      toast.error('Please fill in both title and description');
      return;
    }

    const memory = {
      id: Date.now().toString(),
      ...newMemory,
      date: new Date(),
      users: [currentUser?.user?.id || '', partnerUser?.user?.id || ''],
    };

    addMemoryLaneItem(memory);
    setNewMemory({ title: '', description: '', type: 'milestone' });
    setShowAddMemory(false);
    toast.success('Memory added to your journey!');
  };

  const getMemoryIcon = (type: string) => {
    switch (type) {
      case 'shared_track':
        return <Music className="w-5 h-5" />;
      case 'playlist_created':
        return <Sparkles className="w-5 h-5" />;
      case 'milestone':
        return <Star className="w-5 h-5" />;
      default:
        return <Heart className="w-5 h-5" />;
    }
  };

  const getMemoryColor = (type: string) => {
    switch (type) {
      case 'shared_track':
        return 'from-blue-500 to-cyan-500';
      case 'playlist_created':
        return 'from-purple-500 to-pink-500';
      case 'milestone':
        return 'from-yellow-500 to-orange-500';
      default:
        return 'from-pink-500 to-red-500';
    }
  };

  const MemoryCard = ({ memory, index }: { memory: any; index: number }) => (
    <motion.div
      initial={{ opacity: 0, x: -50 }}
      animate={{ opacity: 1, x: 0 }}
      transition={{ delay: index * 0.1 }}
      className="relative"
    >
      {/* Timeline line */}
      {index < memoryLane.length - 1 && (
        <div className="absolute left-8 top-16 w-0.5 h-full bg-gradient-to-b from-white/20 to-transparent" />
      )}
      
      <div className="flex items-start space-x-6">
        {/* Timeline dot */}
        <div className={`w-16 h-16 rounded-full bg-gradient-to-br ${getMemoryColor(memory.type)} flex items-center justify-center relative z-10`}>
          {getMemoryIcon(memory.type)}
        </div>
        
        {/* Memory content */}
        <motion.div
          whileHover={{ scale: 1.02 }}
          className="glass rounded-2xl p-6 flex-1 border border-white/10"
        >
          <div className="flex items-start justify-between mb-4">
            <div>
              <h3 className="text-xl font-semibold text-white mb-2">{memory.title}</h3>
              <p className="text-white/70 leading-relaxed">{memory.description}</p>
            </div>
            
            <div className="flex items-center space-x-2 text-white/50 text-sm">
              <Calendar className="w-4 h-4" />
              <span>{formatDate(memory.date)}</span>
            </div>
          </div>

          {/* Track preview if it's a shared track */}
          {memory.track && (
            <div className="flex items-center space-x-4 p-4 bg-white/5 rounded-lg">
              <img
                src={memory.track.album.images[0]?.url || '/placeholder-album.png'}
                alt={memory.track.album.name}
                className="w-12 h-12 rounded-lg object-cover"
              />
              <div className="flex-1">
                <h4 className="text-white font-medium">{memory.track.name}</h4>
                <p className="text-white/70 text-sm">{memory.track.artists[0]?.name}</p>
              </div>
              <button className="w-8 h-8 rounded-full bg-spotify-green hover:bg-spotify-green/90 flex items-center justify-center transition-colors">
                <Music className="w-4 h-4 text-white" />
              </button>
            </div>
          )}

          {/* Memory metadata */}
          <div className="flex items-center justify-between mt-4 pt-4 border-t border-white/10">
            <div className="flex items-center space-x-4 text-white/50 text-sm">
              <div className="flex items-center space-x-1">
                <Users className="w-4 h-4" />
                <span>Both of you</span>
              </div>
              <div className="flex items-center space-x-1">
                <Clock className="w-4 h-4" />
                <span>{new Date(memory.date).toLocaleDateString()}</span>
              </div>
            </div>
            
            <button className="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors">
              <Heart className="w-4 h-4 text-white" />
            </button>
          </div>
        </motion.div>
      </div>
    </motion.div>
  );

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="mb-8"
      >
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-4xl font-bold text-white mb-2 flex items-center space-x-3">
              <Heart className="w-10 h-10 text-pink-400" />
              <span>Memory Lane</span>
            </h1>
            <p className="text-white/70 text-lg">
              Your beautiful musical journey together
            </p>
          </div>
          
          <motion.button
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            onClick={() => setShowAddMemory(true)}
            className="bg-gradient-to-r from-pink-500 to-red-500 hover:from-pink-600 hover:to-red-600 text-white font-semibold py-3 px-6 rounded-xl transition-all duration-300 flex items-center space-x-2"
          >
            <Plus className="w-5 h-5" />
            <span>Add Memory</span>
          </motion.button>
        </div>
      </motion.div>

      {/* Add Memory Modal */}
      {showAddMemory && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
          onClick={() => setShowAddMemory(false)}
        >
          <motion.div
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            onClick={(e) => e.stopPropagation()}
            className="glass rounded-2xl p-8 max-w-md w-full"
          >
            <h3 className="text-2xl font-bold text-white mb-6">Add a New Memory</h3>
            
            <div className="space-y-4">
              <div>
                <label className="block text-white/70 text-sm font-medium mb-2">Title</label>
                <input
                  type="text"
                  value={newMemory.title}
                  onChange={(e) => setNewMemory({ ...newMemory, title: e.target.value })}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:border-spotify-green"
                  placeholder="What's this memory about?"
                />
              </div>
              
              <div>
                <label className="block text-white/70 text-sm font-medium mb-2">Description</label>
                <textarea
                  value={newMemory.description}
                  onChange={(e) => setNewMemory({ ...newMemory, description: e.target.value })}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:border-spotify-green h-24 resize-none"
                  placeholder="Tell the story of this memory..."
                />
              </div>
              
              <div>
                <label className="block text-white/70 text-sm font-medium mb-2">Type</label>
                <select
                  value={newMemory.type}
                  onChange={(e) => setNewMemory({ ...newMemory, type: e.target.value as any })}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:border-spotify-green"
                >
                  <option value="milestone">Milestone</option>
                  <option value="shared_track">Shared Track</option>
                  <option value="playlist_created">Playlist Created</option>
                </select>
              </div>
            </div>
            
            <div className="flex items-center space-x-3 mt-6">
              <button
                onClick={handleAddMemory}
                className="flex-1 bg-spotify-green hover:bg-spotify-green/90 text-white font-semibold py-3 px-4 rounded-lg transition-colors"
              >
                Add Memory
              </button>
              <button
                onClick={() => setShowAddMemory(false)}
                className="px-4 py-3 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors"
              >
                Cancel
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}

      {/* Timeline */}
      <div className="space-y-8">
        {memoryLane.length > 0 ? (
          memoryLane.map((memory, index) => (
            <MemoryCard key={memory.id} memory={memory} index={index} />
          ))
        ) : (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="glass rounded-2xl p-12 text-center"
          >
            <Camera className="w-16 h-16 mx-auto mb-4 text-white/30" />
            <h3 className="text-xl font-semibold text-white mb-2">No memories yet</h3>
            <p className="text-white/70 mb-6">
              Start creating beautiful musical memories together
            </p>
            <button
              onClick={() => setShowAddMemory(true)}
              className="bg-gradient-to-r from-pink-500 to-red-500 hover:from-pink-600 hover:to-red-600 text-white font-semibold py-3 px-6 rounded-xl transition-all duration-300"
            >
              Create First Memory
            </button>
          </motion.div>
        )}
      </div>

      {/* Stats */}
      {memoryLane.length > 0 && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.5 }}
          className="mt-12 grid grid-cols-1 md:grid-cols-3 gap-6"
        >
          <div className="glass rounded-2xl p-6 text-center">
            <div className="w-12 h-12 mx-auto mb-3 bg-gradient-to-br from-pink-500 to-red-500 rounded-full flex items-center justify-center">
              <Heart className="w-6 h-6 text-white" />
            </div>
            <h4 className="text-2xl font-bold text-white mb-1">{memoryLane.length}</h4>
            <p className="text-white/70 text-sm">Memories Created</p>
          </div>
          
          <div className="glass rounded-2xl p-6 text-center">
            <div className="w-12 h-12 mx-auto mb-3 bg-gradient-to-br from-blue-500 to-cyan-500 rounded-full flex items-center justify-center">
              <Music className="w-6 h-6 text-white" />
            </div>
            <h4 className="text-2xl font-bold text-white mb-1">
              {memoryLane.filter(m => m.type === 'shared_track').length}
            </h4>
            <p className="text-white/70 text-sm">Shared Tracks</p>
          </div>
          
          <div className="glass rounded-2xl p-6 text-center">
            <div className="w-12 h-12 mx-auto mb-3 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center">
              <Sparkles className="w-6 h-6 text-white" />
            </div>
            <h4 className="text-2xl font-bold text-white mb-1">
              {memoryLane.filter(m => m.type === 'playlist_created').length}
            </h4>
            <p className="text-white/70 text-sm">Playlists Created</p>
          </div>
        </motion.div>
      )}
    </div>
  );
};
