import React, { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { SearchInput } from '../../ui/input';
import {
  Plus,
  PlayCircle,
  Lock,
  Globe,
  Loader2,
  ListMusic,
} from 'lucide-react';
import { Playlist } from '../../../types';
import { useToast } from '../../../context/ToastContext';
import { CreatePlaylistModal } from './CreatePlaylistModal';
import { playlistService } from '../../../services/playlistService';
import { logger } from '@/utils/logger';

export const PlaylistsView: React.FC<{
  onNavigate: (playlistId: string) => void;
}> = ({ onNavigate }) => {
  const { addToast } = useToast();
  const [playlists, setPlaylists] = useState<Playlist[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showCreateModal, setShowCreateModal] = useState(false);

  useEffect(() => {
    loadPlaylists();
  }, []);

  const loadPlaylists = async () => {
    try {
      setLoading(true);
      const response = await playlistService.list();
      setPlaylists(response.playlists || []);
    } catch (error) {
      logger.error('Error loading playlists', {
        error: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
      });
      // Fallback mock
      setPlaylists([
        {
          id: '1',
          title: 'Cyberpunk 2077 Vibes',
          description: 'By Cyber_Producer',
          user_id: 'u1',
          track_count: 45,
          cover_url: 'https://picsum.photos/id/55/400/400',
          tags: ['Synthwave'],
          is_public: true,
          follower_count: 0,
          created_at: '',
          updated_at: '',
        },
        {
          id: '2',
          title: 'Deep Focus Coding',
          description: 'By Cyber_Producer',
          user_id: 'u1',
          track_count: 120,
          cover_url: 'https://picsum.photos/id/60/400/400',
          tags: ['Ambient'],
          is_public: true,
          follower_count: 0,
          created_at: '',
          updated_at: '',
        },
      ]);
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = async (data: any) => {
    try {
      const newPlaylist = await playlistService.create(data);
      setPlaylists([newPlaylist, ...playlists]);
      addToast('Playlist created successfully', 'success');
    } catch (e) {
      addToast('Failed to create playlist', 'error');
    }
  };

  const filtered = playlists.filter((p) =>
    p.title.toLowerCase().includes(search.toLowerCase()),
  );

  return (
    <div className="space-y-6 animate-fadeIn pb-20">
      <div className="flex flex-col md:flex-row justify-between items-end border-b border-kodo-steel/50 pb-6 gap-4">
        <div>
          <h1 className="text-3xl font-display font-bold text-white mb-2">
            MY PLAYLISTS
          </h1>
          <p className="text-gray-400 font-mono text-sm">
            Curate your sonic collection.
          </p>
        </div>
        <Button
          variant="primary"
          icon={<Plus className="w-4 h-4" />}
          onClick={() => setShowCreateModal(true)}
        >
          NEW PLAYLIST
        </Button>
      </div>

      <div className="relative max-w-md">
        <SearchInput
          placeholder="Filter playlists..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      {loading ? (
        <div className="flex justify-center py-20">
          <Loader2 className="w-8 h-8 text-kodo-cyan animate-spin" />
        </div>
      ) : (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
          {filtered.map((playlist) => (
            <Card
              key={playlist.id}
              variant="default"
              className="p-0 overflow-hidden group cursor-pointer hover:border-kodo-cyan/50 transition-all hover:-translate-y-1"
              onClick={() => onNavigate(playlist.id)}
            >
              <div className="aspect-square relative bg-gray-900">
                {playlist.cover_url ? (
                  <img
                    src={playlist.cover_url}
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <div className="w-full h-full flex items-center justify-center text-gray-600">
                    <ListMusic className="w-12 h-12 opacity-50" />
                  </div>
                )}
                <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                  <PlayCircle className="w-12 h-12 text-white fill-current opacity-80 hover:opacity-100 hover:scale-110 transition-all" />
                </div>
                <div className="absolute top-2 right-2">
                  {!playlist.is_public && (
                    <div className="bg-black/60 p-1.5 rounded-full backdrop-blur">
                      <Lock className="w-3 h-3 text-white" />
                    </div>
                  )}
                </div>
              </div>
              <div className="p-4">
                <h3 className="font-bold text-white truncate mb-1">
                  {playlist.title}
                </h3>
                <p className="text-xs text-gray-400 mb-3 line-clamp-1">
                  {playlist.description || 'No description'}
                </p>
                <div className="flex justify-between items-center text-[10px] font-bold text-gray-500 uppercase">
                  <span>{playlist.track_count} Tracks</span>
                  {playlist.is_public ? (
                    <Globe className="w-3 h-3 text-gray-600" />
                  ) : (
                    <Lock className="w-3 h-3 text-gray-600" />
                  )}
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}

      {showCreateModal && (
        <CreatePlaylistModal
          onClose={() => setShowCreateModal(false)}
          onCreate={handleCreate}
        />
      )}
    </div>
  );
};
