import { useState } from 'react';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '../../ui/dialog';
import { ScrollArea } from '../../ui/scroll-area';
import { Card, CardContent } from '../../ui/card';
import { Loader2, Music, Plus } from 'lucide-react';
import type { SpotifyPlaylist } from '../../../types/api';

interface SpotifyPlaylistSelectorProps {
  playlists: SpotifyPlaylist[];
  isLoading: boolean;
  isProcessing?: boolean; // 트랙 추가 중인지 여부
  onPlaylistSelect: (playlistId: string) => void;
  onCreateNew: (playlistName: string, description?: string) => void;
}

export function SpotifyPlaylistSelector({
  playlists,
  isLoading,
  isProcessing = false,
  onPlaylistSelect,
  onCreateNew,
}: SpotifyPlaylistSelectorProps) {
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [newPlaylistName, setNewPlaylistName] = useState('');
  const [newPlaylistDescription, setNewPlaylistDescription] = useState('');

  const handleCreatePlaylist = () => {
    if (!newPlaylistName.trim() || isProcessing) {
      return;
    }

    onCreateNew(newPlaylistName, newPlaylistDescription);
    setShowCreateModal(false);
    setNewPlaylistName('');
    setNewPlaylistDescription('');
  };

  const handlePlaylistClick = (playlistId: string) => {
    if (isProcessing) {
      return;
    }
    onPlaylistSelect(playlistId);
  };

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-12">
        <Loader2 className="size-8 animate-spin text-primary mb-3" />
        <p className="text-sm text-muted-foreground">플레이리스트를 불러오는 중...</p>
      </div>
    );
  }

  if (isProcessing) {
    return (
      <div className="flex flex-col items-center justify-center py-12">
        <Loader2 className="size-8 animate-spin text-primary mb-3" />
        <p className="text-sm text-muted-foreground">트랙을 추가하는 중...</p>
        <p className="text-xs text-muted-foreground mt-2">잠시만 기다려주세요</p>
      </div>
    );
  }

  return (
    <>
      <div className="space-y-4">
        {/* 새 플레이리스트 생성 버튼 */}
        <Card
          className={`cursor-pointer hover:bg-primary/5 transition-colors border-dashed border-2 border-primary/30 ${isProcessing ? 'opacity-50 cursor-not-allowed' : ''}`}
          onClick={() => !isProcessing && setShowCreateModal(true)}
        >
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-primary/10 rounded-lg">
                <Plus className="size-5 text-primary" />
              </div>
              <div>
                <p className="font-medium text-primary">새 플레이리스트에 넣기</p>
                <p className="text-xs text-muted-foreground">새로운 플레이리스트를 생성합니다</p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 기존 플레이리스트 목록 */}
        <ScrollArea className="h-[400px] pr-4">
          <div className="space-y-2">
            {playlists.map((playlist) => {
              const imageUrl = playlist.images && playlist.images.length > 0
                ? playlist.images[0].url
                : null;

              return (
                <Card
                  key={playlist.playlist_id}
                  className={`cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/80 transition-all ${isProcessing ? 'opacity-50 cursor-not-allowed' : ''}`}
                  onClick={() => handlePlaylistClick(playlist.playlist_id)}
                >
                  <CardContent className="p-4">
                    <div className="flex items-center gap-3">
                      {/* 플레이리스트 이미지 */}
                      <div className="size-14 rounded-lg overflow-hidden shrink-0 bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
                        {imageUrl ? (
                          <img
                            src={imageUrl}
                            alt={playlist.playlist_name}
                            className="size-full object-cover"
                          />
                        ) : (
                          <Music className="size-6 text-gray-400 dark:text-gray-500" />
                        )}
                      </div>

                      {/* 플레이리스트 정보 */}
                      <div className="flex-1 min-w-0">
                        <p className="truncate text-sm font-medium text-foreground">
                          {playlist.playlist_name}
                        </p>
                        <div className="flex items-center gap-2 mt-1">
                          <span className="text-xs text-muted-foreground flex items-center gap-1">
                            <Music className="size-3" />
                            {playlist.track_count ?? 0}곡
                          </span>
                          {playlist.is_public && (
                            <span className="text-xs text-muted-foreground">• 공개</span>
                          )}
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </ScrollArea>
      </div>

      {/* 새 플레이리스트 생성 모달 */}
      <Dialog open={showCreateModal} onOpenChange={setShowCreateModal}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>새 플레이리스트 생성</DialogTitle>
            <DialogDescription>
              새로운 Spotify 플레이리스트를 생성하고 곡을 추가합니다.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="playlist-name">플레이리스트 이름 *</Label>
              <Input
                id="playlist-name"
                placeholder="플레이리스트 이름을 입력하세요"
                value={newPlaylistName}
                onChange={(e) => setNewPlaylistName(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleCreatePlaylist()}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="playlist-description">설명 (선택)</Label>
              <Input
                id="playlist-description"
                placeholder="플레이리스트 설명을 입력하세요"
                value={newPlaylistDescription}
                onChange={(e) => setNewPlaylistDescription(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleCreatePlaylist()}
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setShowCreateModal(false);
                setNewPlaylistName('');
                setNewPlaylistDescription('');
              }}
            >
              취소
            </Button>
            <Button
              onClick={handleCreatePlaylist}
              disabled={!newPlaylistName.trim() || isProcessing}
            >
              {isProcessing ? (
                <>
                  <Loader2 className="size-4 mr-2 animate-spin" />
                  처리 중...
                </>
              ) : (
                '생성 및 추가'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
