import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { apiService, type Playlist, type Track } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import { 
  Loader2, 
  Plus, 
  Music, 
  Play, 
  Trash2, 
  Edit,
  Search,
  ListMusic,
  Lock,
  Globe,
  MoreVertical,
  Users
} from 'lucide-react';
import { PlaylistEditor } from '../components/PlaylistEditor';

export function PlaylistsPage() {
  const [playlists, setPlaylists] = useState<Playlist[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedPlaylist, setSelectedPlaylist] = useState<Playlist | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const { toast } = useToast();

  // Form state pour créer/éditer une playlist
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    isPublic: false,
  });

  const fetchPlaylists = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const data = await apiService.getPlaylists();
      setPlaylists(data);
    } catch (err: any) {
      setError(err.response?.data?.error || err.message || 'Failed to fetch playlists');
      console.error('Error fetching playlists:', err);
    } finally {
      setIsLoading(false);
    }
  };

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

  const handleCreatePlaylist = async () => {
    if (!formData.name.trim()) {
      toast({
        title: 'Name required',
        description: 'Please enter a playlist name',
        variant: 'destructive',
      });
      return;
    }

    try {
      setIsCreating(true);
      const newPlaylist = await apiService.createPlaylist({
        name: formData.name,
        description: formData.description || undefined,
        isPublic: formData.isPublic,
      });
      
      toast({
        title: 'Playlist created',
        description: `"${newPlaylist.name}" has been created successfully.`,
      });
      
      setFormData({ name: '', description: '', isPublic: false });
      setIsEditDialogOpen(false);
      fetchPlaylists();
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.response?.data?.error || 'Failed to create playlist',
        variant: 'destructive',
      });
    } finally {
      setIsCreating(false);
    }
  };

  const handleUpdatePlaylist = async () => {
    if (!selectedPlaylist) return;

    try {
      const updated = await apiService.updatePlaylist(selectedPlaylist.id, {
        name: formData.name,
        description: formData.description || undefined,
        isPublic: formData.isPublic,
      });
      
      toast({
        title: 'Playlist updated',
        description: `"${updated.name}" has been updated.`,
      });
      
      setSelectedPlaylist(null);
      setIsEditDialogOpen(false);
      fetchPlaylists();
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.response?.data?.error || 'Failed to update playlist',
        variant: 'destructive',
      });
    }
  };

  const handleDeletePlaylist = async (playlistId: string, name: string) => {
    if (!confirm(`Are you sure you want to delete "${name}"?`)) return;

    try {
      await apiService.deletePlaylist(playlistId);
      toast({
        title: 'Playlist deleted',
        description: `"${name}" has been deleted.`,
      });
      fetchPlaylists();
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.response?.data?.error || 'Failed to delete playlist',
        variant: 'destructive',
      });
    }
  };

  const openEditDialog = (playlist?: Playlist) => {
    if (playlist) {
      setSelectedPlaylist(playlist);
      setFormData({
        name: playlist.name,
        description: playlist.description || '',
        isPublic: playlist.isPublic,
      });
    } else {
      setSelectedPlaylist(null);
      setFormData({ name: '', description: '', isPublic: false });
    }
    setIsEditDialogOpen(true);
  };

  const filteredPlaylists = playlists.filter(playlist =>
    playlist.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    playlist.description?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  if (isLoading) {
    return (
      <div className="flex items-center justify-center p-8">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Playlists</h1>
        <p className="text-muted-foreground">
          Create and manage your music playlists
        </p>
      </div>

      {/* Toolbar */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center justify-between space-x-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Search playlists..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
              />
            </div>
            
            <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
              <DialogTrigger asChild>
                <Button onClick={() => openEditDialog()}>
                  <Plus className="h-4 w-4 mr-2" />
                  New Playlist
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>
                    {selectedPlaylist ? 'Edit Playlist' : 'Create New Playlist'}
                  </DialogTitle>
                  <DialogDescription>
                    {selectedPlaylist 
                      ? 'Update your playlist details' 
                      : 'Create a new playlist to organize your tracks'
                    }
                  </DialogDescription>
                </DialogHeader>
                
                <div className="space-y-4 py-4">
                  <div className="space-y-2">
                    <Label htmlFor="name">Name *</Label>
                    <Input
                      id="name"
                      placeholder="My Awesome Playlist"
                      value={formData.name}
                      onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                    />
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="description">Description</Label>
                    <Textarea
                      id="description"
                      placeholder="Optional description..."
                      value={formData.description}
                      onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                      rows={3}
                    />
                  </div>
                  
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="isPublic"
                      checked={formData.isPublic}
                      onChange={(e) => setFormData(prev => ({ ...prev, isPublic: e.target.checked }))}
                      className="h-4 w-4"
                    />
                    <Label htmlFor="isPublic" className="cursor-pointer">
                      Make this playlist public
                    </Label>
                  </div>
                </div>
                
                <DialogFooter>
                  <Button
                    variant="outline"
                    onClick={() => setIsEditDialogOpen(false)}
                  >
                    Cancel
                  </Button>
                  <Button
                    onClick={selectedPlaylist ? handleUpdatePlaylist : handleCreatePlaylist}
                    disabled={isCreating}
                  >
                    {isCreating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                    {selectedPlaylist ? 'Update' : 'Create'}
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </CardContent>
      </Card>

      {/* Error Display */}
      {error && (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center text-red-500">
              Error loading playlists: {error}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Playlists Grid */}
      {filteredPlaylists.length === 0 ? (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-8">
              <ListMusic className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <h3 className="text-lg font-medium mb-2">No Playlists Yet</h3>
              <p className="text-muted-foreground mb-4">
                {searchQuery 
                  ? 'No playlists match your search.' 
                  : 'Create your first playlist to start organizing your music.'
                }
              </p>
              {!searchQuery && (
                <Button onClick={() => openEditDialog()}>
                  <Plus className="h-4 w-4 mr-2" />
                  Create Playlist
                </Button>
              )}
            </div>
          </CardContent>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {filteredPlaylists.map((playlist) => (
            <Card 
              key={playlist.id} 
              className="group hover:shadow-lg transition-all cursor-pointer"
              onClick={() => {
                // Navigate to playlist detail
                window.location.href = `/playlists/${playlist.id}`;
              }}
            >
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <CardTitle className="truncate">{playlist.name}</CardTitle>
                    <CardDescription className="line-clamp-2">
                      {playlist.description || 'No description'}
                    </CardDescription>
                  </div>
                  <div className="flex items-center space-x-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={(e) => {
                        e.stopPropagation();
                        openEditDialog(playlist);
                      }}
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleDeletePlaylist(playlist.id, playlist.name);
                      }}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">
                      {playlist.tracks?.length || 0} tracks
                    </span>
                    <Badge variant={playlist.isPublic ? 'default' : 'secondary'}>
                      {playlist.isPublic ? (
                        <>
                          <Globe className="h-3 w-3 mr-1" />
                          Public
                        </>
                      ) : (
                        <>
                          <Lock className="h-3 w-3 mr-1" />
                          Private
                        </>
                      )}
                    </Badge>
                  </div>
                  
                  <div className="text-xs text-muted-foreground">
                    Created {new Date(playlist.createdAt).toLocaleDateString()}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Stats */}
      <Card>
        <CardContent className="pt-6">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
            <div>
              <div className="text-2xl font-bold">{playlists.length}</div>
              <div className="text-sm text-muted-foreground">Total Playlists</div>
            </div>
            <div>
              <div className="text-2xl font-bold">
                {playlists.filter(p => p.isPublic).length}
              </div>
              <div className="text-sm text-muted-foreground">Public</div>
            </div>
            <div>
              <div className="text-2xl font-bold">
                {playlists.reduce((sum, p) => sum + (p.tracks?.length || 0), 0)}
              </div>
              <div className="text-sm text-muted-foreground">Total Tracks</div>
            </div>
            <div>
              <div className="text-2xl font-bold">
                {Math.round(playlists.reduce((sum, p) => sum + (p.tracks?.length || 0), 0) / (playlists.length || 1))}
              </div>
              <div className="text-sm text-muted-foreground">Avg Tracks/Playlist</div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

export default PlaylistsPage;

