import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "../../ui/dialog";
import { Button } from "../../ui/button";
import { Input } from "../../ui/input";
import { Label } from "../../ui/label";
import { Progress } from "../../ui/progress";
import { Separator } from "../../ui/separator";
import { ScrollArea } from "../../ui/scroll-area";
import { CheckCircle, Loader2, ArrowRight } from "lucide-react";
import { motion } from "motion/react";

interface TransferDialogProps {
  open: boolean;
  onClose: () => void;
  selectedCount: number;
  services: { name: string; icon: string; color: string }[];
  onComplete: () => void;
}

export function TransferDialog({
  open,
  onClose,
  selectedCount,
  services,
  onComplete,
}: TransferDialogProps) {
  const [selectedService, setSelectedService] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [transferring, setTransferring] = useState(false);
  const [progress, setProgress] = useState(0);
  const [complete, setComplete] = useState(false);

  const handleTransfer = async () => {
    setTransferring(true);
    setProgress(0);

    // Simulate transfer progress
    const interval = setInterval(() => {
      setProgress((prev) => {
        if (prev >= 100) {
          clearInterval(interval);
          setComplete(true);
          setTimeout(() => {
            onComplete();
            handleClose();
          }, 2000);
          return 100;
        }
        return prev + 10;
      });
    }, 300);
  };

  const handleClose = () => {
    setSelectedService("");
    setEmail("");
    setPassword("");
    setTransferring(false);
    setProgress(0);
    setComplete(false);
    onClose();
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[540px]">
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.2 }}
        >
          <DialogHeader>
            <DialogTitle className="text-2xl">플레이리스트 이전</DialogTitle>
            <DialogDescription className="text-base">
              {selectedCount}개의 플레이리스트를 이전할 서비스를 선택하세요.
            </DialogDescription>
          </DialogHeader>
          
          <Separator className="my-6" />
          
          {!transferring && !complete && (
            <div className="space-y-6">
              <div className="space-y-3">
                <Label className="text-base">이전할 서비스 선택</Label>
                <ScrollArea className="h-auto max-h-[200px]">
                  <div className="grid grid-cols-3 gap-3 pr-4">
                    {services.map((service, index) => (
                      <motion.button
                        key={service.name}
                        onClick={() => setSelectedService(service.name)}
                        className={`p-4 rounded-xl border-2 flex flex-col items-center gap-3 transition-all ${
                          selectedService === service.name
                            ? "border-primary bg-primary/5 dark:bg-primary/10 shadow-md ring-2 ring-primary/20"
                            : "border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800"
                        }`}
                        initial={{ opacity: 0, scale: 0.8 }}
                        animate={{ opacity: 1, scale: 1 }}
                        transition={{ 
                          delay: index * 0.05,
                          type: "spring",
                          stiffness: 300,
                          damping: 20
                        }}
                        whileHover={{ scale: 1.05, y: -2 }}
                        whileTap={{ scale: 0.98 }}
                      >
                        <div 
                          className="w-12 h-12 rounded-xl flex items-center justify-center shadow-sm"
                          style={{ backgroundColor: service.color }}
                        >
                          <span className="text-2xl">{service.icon}</span>
                        </div>
                        <span className="text-xs text-center leading-tight">{service.name}</span>
                        {selectedService === service.name && (
                          <motion.div
                            initial={{ scale: 0 }}
                            animate={{ scale: 1 }}
                            transition={{ type: "spring", stiffness: 500, damping: 25 }}
                          >
                            <CheckCircle className="size-4 text-primary" />
                          </motion.div>
                        )}
                      </motion.button>
                    ))}
                  </div>
                </ScrollArea>
              </div>

              {selectedService && (
                <motion.div
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: "auto" }}
                  transition={{ duration: 0.3 }}
                  className="space-y-5 overflow-hidden"
                >
                  <Separator />
                  
                  <div className="bg-primary/5 dark:bg-primary/10 rounded-xl p-4 border border-primary/10 dark:border-primary/20">
                    <p className="text-sm text-muted-foreground">
                      <strong className="text-foreground">{selectedService}</strong> 계정으로 로그인하여 플레이리스트를 이전합니다.
                    </p>
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="transfer-email">이메일 주소</Label>
                    <Input
                      id="transfer-email"
                      type="email"
                      placeholder="example@email.com"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="h-11"
                    />
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="transfer-password">비밀번호</Label>
                    <Input
                      id="transfer-password"
                      type="password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="h-11"
                    />
                  </div>
                  
                  <Button onClick={handleTransfer} className="w-full h-12 shadow-md" size="lg">
                    <ArrowRight className="size-5 mr-2" />
                    인증하고 이전 시작
                  </Button>
                </motion.div>
              )}
            </div>
          )}

          {transferring && !complete && (
            <motion.div 
              className="space-y-6 py-8"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
            >
              <div className="text-center space-y-4">
                <motion.div
                  animate={{ rotate: 360 }}
                  transition={{ 
                    duration: 2, 
                    repeat: Infinity, 
                    ease: "linear" 
                  }}
                  className="inline-block"
                >
                  <div className="p-4 bg-primary/10 dark:bg-primary/20 rounded-2xl">
                    <Loader2 className="size-12 text-primary" />
                  </div>
                </motion.div>
                <div>
                  <h3 className="mb-2">플레이리스트를 이전하는 중...</h3>
                  <p className="text-muted-foreground">
                    잠시만 기다려 주세요
                  </p>
                </div>
              </div>
              
              <div className="space-y-3">
                <Progress value={progress} className="h-3" />
                <motion.p 
                  className="text-center text-sm text-muted-foreground"
                  key={progress}
                  initial={{ scale: 1.1, opacity: 0.7 }}
                  animate={{ scale: 1, opacity: 1 }}
                  transition={{ duration: 0.2 }}
                >
                  {progress}% 완료
                </motion.p>
              </div>
            </motion.div>
          )}

          {complete && (
            <motion.div 
              className="py-12 flex flex-col items-center gap-6"
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ 
                type: "spring",
                stiffness: 200,
                damping: 15
              }}
            >
              <motion.div
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                transition={{
                  type: "spring",
                  stiffness: 260,
                  damping: 20,
                  delay: 0.1
                }}
                className="p-6 bg-green-50 dark:bg-green-950/50 rounded-full"
              >
                <CheckCircle className="size-20 text-green-500" />
              </motion.div>
              
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.2 }}
                className="text-center space-y-2"
              >
                <h3>이전이 완료되었습니다!</h3>
                <p className="text-muted-foreground">
                  {selectedCount}개의 플레이리스트가 성공적으로 이전되었습니다.
                </p>
              </motion.div>
            </motion.div>
          )}
        </motion.div>
      </DialogContent>
    </Dialog>
  );
}