import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { ServiceCard } from "./components/features/service/ServiceCard";
import { ServiceSelectionDialog } from "./components/features/service/ServiceSelectionDialog";
import { PlaylistView } from "./components/features/playlist/PlaylistView";
import { TransferDialog } from "./components/features/playlist/TransferDialog";
import { ThemeToggle } from "./components/common/ThemeToggle";
import { Button } from "./components/ui/button";
import { Input } from "./components/ui/input";
import { Avatar, AvatarFallback } from "./components/ui/avatar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "./components/ui/dropdown-menu";
import { Menu, User, HelpCircle, Music2, Download, Upload, History, Search, Sparkles } from "lucide-react";
import Alert from "./utils/alert";
import { motion, AnimatePresence } from "motion/react";
import { streamingServices } from "./constants/streamingServices";

interface Playlist {
  id: number;
  name: string;
  trackCount: number;
  selected: boolean;
}

export default function App() {
  const navigate = useNavigate();
  const [selectedService, setSelectedService] = useState<string | null>(null);
  const [playlists, setPlaylists] = useState<Playlist[]>([]);
  const [showTransferDialog, setShowTransferDialog] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");

  const handleServiceClick = (serviceName: string) => {
    if (serviceName === "VIBE") {
      navigate("/vibe");
    } else {
      setSelectedService(serviceName);
    }
  };

  const handleLoadPlaylists = (newPlaylists: Playlist[]) => {
    setPlaylists(newPlaylists);
    Alert.success("플레이리스트를 성공적으로 가져왔습니다!");
  };

  const handleTogglePlaylist = (id: number) => {
    setPlaylists(
      playlists.map((p) =>
        p.id === id ? { ...p, selected: !p.selected } : p
      )
    );
  };

  const handleTransferClick = () => {
    setShowTransferDialog(true);
  };

  const handleTransferComplete = () => {
    Alert.success("플레이리스트 이전이 완료되었습니다!");
    setPlaylists([]);
  };

  const handleLogin = () => {
    setIsLoggedIn(!isLoggedIn);
    Alert.success(isLoggedIn ? "로그아웃되었습니다." : "로그인되었습니다.");
  };

  const selectedCount = playlists.filter((p) => p.selected).length;

  const filteredServices = streamingServices.filter((service) =>
    service.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-gray-50 to-purple-50/30 dark:from-gray-900 dark:via-gray-950 dark:to-blue-950/30 transition-colors duration-300">
      {/* Header */}
      <motion.header 
        className="bg-white/80 dark:bg-gray-900/80 backdrop-blur-lg border-b dark:border-gray-800 sticky top-0 z-10 shadow-sm transition-colors duration-300"
        initial={{ y: -100 }}
        animate={{ y: 0 }}
        transition={{ duration: 0.5, ease: "easeOut" }}
      >
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <motion.div 
              className="flex items-center gap-3"
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.2 }}
            >
              <motion.div
                animate={{ rotate: [0, 10, -10, 0] }}
                transition={{
                  duration: 2,
                  repeat: Infinity,
                  repeatDelay: 3
                }}
                className="p-1.5 sm:p-2 bg-primary/10 rounded-xl"
              >
                  <Music2 className="size-5 sm:size-7 text-primary" />
              </motion.div>
              <div>
                <h1 className="flex items-center gap-1.5 sm:gap-2 text-lg sm:text-2xl">
                  <span className="hidden xs:inline">Playlist Transfer</span>
                  <span className="xs:hidden">MyListBridge</span>
                  <Sparkles className="size-4 sm:size-5 text-primary" />
                </h1>
                <p className="text-xs text-muted-foreground hidden sm:block">손쉬운 플레이리스트 이전 서비스</p>
              </div>
            </motion.div>
            
            <div className="flex items-center gap-1.5 sm:gap-3">
              {isLoggedIn ? (
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" className="gap-1.5 sm:gap-2 px-2 sm:px-3">
                      <Avatar className="size-6 sm:size-7">
                        <AvatarFallback className="bg-primary/10 text-primary text-xs">U</AvatarFallback>
                      </Avatar>
                      <span className="hidden sm:inline">내 계정</span>
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end" className="w-48">
                    <DropdownMenuItem>
                      <User className="size-4 mr-2" />
                      프로필 설정
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={handleLogin}>
                      로그아웃
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              ) : (
                <Button variant="default" onClick={handleLogin} className="shadow-md text-sm sm:text-base px-3 sm:px-4">
                  <User className="size-3.5 sm:size-4 sm:mr-2" />
                  <span className="hidden sm:inline">로그인</span>
                </Button>
              )}

              <ThemeToggle />

              <Button variant="outline" className="gap-1.5 sm:gap-2 px-2 sm:px-4 hidden md:flex">
                <HelpCircle className="size-4" />
                <span>도움말</span>
              </Button>

              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline" size="icon" className="size-9 sm:size-10">
                    <Menu className="size-4 sm:size-5" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-56">
                  <DropdownMenuItem>
                    <Download className="size-4 mr-2" />
                    플레이리스트 내보내기
                  </DropdownMenuItem>
                  <DropdownMenuItem>
                    <Upload className="size-4 mr-2" />
                    플레이리스트 가져오기
                  </DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem>
                    <History className="size-4 mr-2" />
                    이전 기록 보기
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
        </div>
      </motion.header>

      {/* Main Content */}
      <main className="container mx-auto px-3 sm:px-4 py-6 sm:py-12">
        <div className="max-w-7xl mx-auto space-y-8 sm:space-y-12">
          {/* Services Section */}
          <section>
            <motion.div
              className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4 mb-6 sm:mb-8"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
            >
              <div>
                <h2 className="mb-1 sm:mb-2 text-xl sm:text-2xl">스트리밍 서비스 선택</h2>
                <p className="text-muted-foreground text-sm sm:text-base">
                  연결할 음악 스트리밍 서비스를 선택하세요
                </p>
              </div>

              <div className="relative w-full sm:w-72">
                <Search className="size-4 sm:size-5 absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground" />
                <Input
                  type="text"
                  placeholder="서비스 검색..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-9 sm:pl-10 h-10 sm:h-11 bg-white dark:bg-gray-900 shadow-sm text-sm sm:text-base"
                />
              </div>
            </motion.div>
            
            <motion.div
              className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-6"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.4 }}
            >
              <AnimatePresence mode="popLayout">
                {filteredServices.map((service, index) => (
                  <ServiceCard
                    key={service.name}
                    name={service.name}
                    icon={service.icon}
                    color={service.color}
                    imageUrl={service.imageUrl}
                    onClick={() => handleServiceClick(service.name)}
                    index={index}
                  />
                ))}
              </AnimatePresence>
            </motion.div>
            
            <AnimatePresence>
              {filteredServices.length === 0 && (
                <motion.div 
                  className="text-center py-16"
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.9 }}
                >
                  <p className="text-muted-foreground">검색 결과가 없습니다.</p>
                </motion.div>
              )}
            </AnimatePresence>
          </section>

          {/* Playlists Section */}
          <AnimatePresence>
            {playlists.length > 0 && (
              <section>
                <PlaylistView
                  playlists={playlists}
                  onTogglePlaylist={handleTogglePlaylist}
                  onTransfer={handleTransferClick}
                />
              </section>
            )}
          </AnimatePresence>

          {/* Empty State */}
          <AnimatePresence>
            {playlists.length === 0 && (
              <motion.section 
                className="text-center py-20"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                transition={{ delay: 0.6 }}
              >
                <motion.div
                  animate={{ 
                    y: [0, -10, 0],
                  }}
                  transition={{ 
                    duration: 2, 
                    repeat: Infinity,
                    ease: "easeInOut"
                  }}
                  className="inline-block mb-6 p-6 bg-primary/5 dark:bg-primary/10 rounded-3xl"
                >
                  <Music2 className="size-20 text-primary" />
                </motion.div>
                <h3 className="text-xl text-foreground mb-3">스트리밍 서비스를 선택하세요</h3>
                <p className="text-muted-foreground max-w-md mx-auto">
                  위의 서비스 중 하나를 선택하여 플레이리스트를 가져오고 다른 서비스로 이전할 수 있습니다.
                </p>
              </motion.section>
            )}
          </AnimatePresence>
        </div>
      </main>

      {/* Dialogs */}
      <ServiceSelectionDialog
        open={selectedService !== null}
        onClose={() => setSelectedService(null)}
        serviceName={selectedService || ""}
        onLoadPlaylists={handleLoadPlaylists}
      />

      <TransferDialog
        open={showTransferDialog}
        onClose={() => setShowTransferDialog(false)}
        selectedCount={selectedCount}
        services={streamingServices}
        onComplete={handleTransferComplete}
      />
    </div>
  );
}