import { useLoaderData, useParams } from "react-router-dom";
import { client } from "../../lib/client";
import { defineChain } from "thirdweb";
import { ClaimButton, useActiveAccount } from "thirdweb/react";
import ShortenAddress from "../../lib/ShortenAddress";
import { useState } from "react";
import { motion } from "framer-motion";
import {
  FaArrowRight,
  FaIdCard,
  FaMinusCircle,
  FaPlusCircle,
  FaSpinner,
  FaTasks,
} from "react-icons/fa";
import { FaXTwitter } from "react-icons/fa6";
import { AiOutlineRetweet } from "react-icons/ai";
import { SiDiscord } from "react-icons/si";
import { LuCircleDollarSign } from "react-icons/lu";
import { MdTaskAlt } from "react-icons/md";
import { RxOpenInNewWindow } from "react-icons/rx";
import ChainLogo from "../../components/ChainLogo/ChainLogo";
import ThirdConnect from "../../components/ThirdConnect/ThirdConnect";
import Footer from "../../Shared/Footer/Footer";

const taskIcon = (title = "") => {
  const name = title.toLowerCase();
  if (name.includes("discord")) return <SiDiscord />;
  if (name.includes("retweet") || name.includes("repost")) return <AiOutlineRetweet />;
  if (name.includes("id")) return <FaIdCard />;
  return <FaXTwitter />;
};

const NFTCheckout = () => {
  const nfts = useLoaderData();
  const { uriName } = useParams();
  const nft = nfts?.find((item) => item.uriName === uriName);
  const chain = defineChain(nft?.chain ?? 1);
  const activeAccount = useActiveAccount();

  const [tasks, setTasks] = useState(nft?.tasks ?? []);
  const [loadingTask, setLoadingTask] = useState(null);
  const [quantity, setQuantity] = useState(1);
  const [mintStatus, setMintStatus] = useState("");
  const [mintPending, setMintPending] = useState(false);
  const [mintError, setMintError] = useState("");
  const [mintTxHash, setMintTxHash] = useState("");

  const completeTask = (taskId, link) => {
    setLoadingTask(taskId);
    if (link) window.open(link, "_blank", "noopener,noreferrer");

    window.setTimeout(() => {
      setTasks((previous) =>
        previous.map((task) =>
          task.id === taskId ? { ...task, completed: true } : task
        )
      );
      setLoadingTask(null);
    }, 15000);
  };

  const allTasksCompleted = tasks.every((task) => task.completed);
  const completedTasks = tasks.filter((task) => task.completed).length;
  const progress = tasks.length ? (completedTasks / tasks.length) * 100 : 0;

  return (
    <div className="relative min-h-screen overflow-hidden pb-10">
      <div className="pointer-events-none absolute left-[-12rem] top-20 h-[32rem] w-[32rem] rounded-full bg-violet-600/[0.12] blur-[120px]" />
      <div className="pointer-events-none absolute right-[-12rem] top-[28rem] h-[30rem] w-[30rem] rounded-full bg-cyan-500/[0.07] blur-[120px]" />

      <main className="relative z-10 mx-auto max-w-7xl px-4 pb-12 pt-28 sm:px-6 lg:px-8 lg:pt-32">
        {!nft ? (
          <div className="mx-auto max-w-xl rounded-3xl border border-white/10 bg-slate-950/70 p-8 text-center text-slate-300 backdrop-blur-xl">
            This NFT collection could not be found.
          </div>
        ) : (
          <section className="grid items-center gap-8 lg:grid-cols-[minmax(300px,0.82fr)_minmax(0,1.18fr)] lg:gap-12">
            <motion.div
              initial={{ opacity: 0, x: -24, y: 8 }}
              animate={{ opacity: 1, x: 0, y: 0 }}
              transition={{ duration: 0.55, ease: "easeOut" }}
              className="mx-auto w-full max-w-[440px]"
            >
              <div className="overflow-hidden rounded-[28px] border border-violet-300/25 bg-gradient-to-b from-[#17152b]/95 via-[#0e1020]/95 to-[#090b14]/95 shadow-[0_28px_90px_rgba(30,22,99,.34),0_0_55px_rgba(84,67,218,.12)] backdrop-blur-2xl">
                <div className="flex items-center justify-between border-b border-violet-200/10 bg-gradient-to-r from-violet-500/[0.16] via-indigo-500/[0.1] to-cyan-400/[0.07] px-5 py-4">
                  <div className="flex min-w-0 items-center gap-2.5">
                    <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/15 bg-gradient-to-br from-violet-500 to-cyan-400 text-xs font-black text-white shadow-lg shadow-violet-900/40">A</span>
                    <span className="truncate text-[11px] font-bold uppercase tracking-[.2em] text-violet-100/90">{nft.name}</span>
                  </div>
                  <span className="inline-flex shrink-0 items-center gap-2 rounded-full border border-emerald-300/15 bg-emerald-300/[0.07] px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider text-emerald-300">
                    <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-emerald-300" />
                    Live
                  </span>
                </div>

                <div className="relative isolate aspect-square overflow-hidden bg-[#080a15] p-4 sm:p-5">
                  <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_at_30%_25%,rgba(99,74,235,.2),transparent_48%),radial-gradient(ellipse_at_80%_80%,rgba(24,174,214,.12),transparent_44%)]" />
                  <div className="pointer-events-none absolute inset-4 rounded-2xl border border-white/[0.07]" />
                  <img
                    className="relative z-10 h-full w-full rounded-2xl object-contain drop-shadow-[0_16px_42px_rgba(83,75,220,.24)]"
                    src={nft.image}
                    alt={`${nft.name} NFT artwork`}
                  />
                </div>

                <div className="border-t border-white/[0.06] px-5 py-5 sm:px-6">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <h2 className="truncate text-xl font-bold tracking-tight text-white sm:text-2xl">{nft.name}</h2>
                      <p className="mt-1 text-xs text-slate-500">ALZE onchain collection</p>
                    </div>
                    <span className="inline-flex max-w-[52%] shrink-0 items-center gap-1.5 truncate rounded-full border border-violet-300/20 bg-violet-300/[0.07] px-2.5 py-1.5 text-[10px] font-semibold text-violet-100/85">
                      <ChainLogo chainId={nft.chain} chainName={nft.blockChain} size={15} />
                      <span className="truncate">{nft.blockChain}</span>
                    </span>
                  </div>

                  <div className="mt-5 grid grid-cols-2 gap-3">
                    <div className="rounded-2xl border border-violet-300/15 bg-violet-400/[0.07] px-4 py-3">
                      <p className="text-[10px] font-bold uppercase tracking-[.16em] text-slate-500">Mint price</p>
                      <p className="mt-1 flex items-center gap-2 text-base font-bold text-violet-100">
                        <LuCircleDollarSign className="text-violet-300" />
                        {nft.price > 0 ? `${nft.price} ${nft.priceCurrency || "ETH"}` : "Free"}
                      </p>
                    </div>
                    <div className="min-w-0 rounded-2xl border border-cyan-300/15 bg-cyan-400/[0.055] px-4 py-3">
                      <p className="text-[10px] font-bold uppercase tracking-[.16em] text-slate-500">Contract</p>
                      <div className="mt-1 truncate text-sm font-semibold text-cyan-100">
                        <ShortenAddress address={nft.address} />
                      </div>
                    </div>
                  </div>

                  {nft.explorerLink && (
                    <a className="mt-4 inline-flex items-center gap-1.5 text-xs font-semibold text-slate-400 transition hover:text-cyan-200" href={nft.explorerLink} target="_blank" rel="noopener noreferrer">
                      View on explorer <RxOpenInNewWindow />
                    </a>
                  )}
                </div>
              </div>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, x: 24, y: 8 }}
              animate={{ opacity: 1, x: 0, y: 0 }}
              transition={{ duration: 0.55, delay: 0.08, ease: "easeOut" }}
              className="rounded-[28px] border border-violet-300/20 bg-gradient-to-br from-[#121025]/95 via-[#0c0b1c]/95 to-[#080912]/95 p-5 shadow-[0_30px_100px_rgba(0,0,0,.35),inset_0_1px_rgba(255,255,255,.035)] backdrop-blur-2xl sm:p-7 lg:p-8"
            >
              <div className="mb-6">
                <span className="inline-flex items-center gap-2 rounded-full border border-violet-300/25 bg-violet-400/[0.09] px-3 py-1.5 text-[10px] font-bold uppercase tracking-[.18em] text-violet-200">
                  <FaTasks /> Claim NFT
                </span>
                <h1 className="mt-4 text-2xl font-bold tracking-tight text-white sm:text-3xl">Claim your {nft.name}</h1>
                <p className="mt-2 max-w-2xl text-sm leading-6 text-slate-400">
                  {nft.description || `Complete the tasks below to unlock your ${nft.name}.`}
                </p>
              </div>

              {tasks.length > 0 ? (
                <>
                  <div className="space-y-2.5">
                    {tasks.map((task, index) => (
                      <motion.div
                        key={task.id}
                        initial={{ opacity: 0, y: 8 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ duration: 0.25, delay: index * 0.045 }}
                        className={`flex min-h-[66px] items-center justify-between gap-4 rounded-2xl border px-3.5 py-3 transition sm:px-4 ${task.completed ? "border-emerald-300/20 bg-emerald-300/[0.045]" : "border-white/[0.07] bg-white/[0.025] hover:border-violet-300/20 hover:bg-violet-300/[0.045]"}`}
                      >
                        <div className="flex min-w-0 items-center gap-3">
                          <span className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border ${task.completed ? "border-emerald-300/20 bg-emerald-300/[0.08] text-emerald-200" : "border-white/[0.07] bg-white/[0.035] text-violet-200"}`}>
                            {task.completed ? <MdTaskAlt size={17} /> : taskIcon(task.title)}
                          </span>
                          <span className={`truncate text-sm font-semibold ${task.completed ? "text-slate-400 line-through" : "text-slate-100"}`}>{task.title}</span>
                        </div>
                        <button
                          type="button"
                          className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full border transition ${task.completed ? "border-emerald-300/20 text-emerald-300" : "border-violet-200/15 bg-white/[0.025] text-violet-100 hover:border-violet-200/40 hover:bg-violet-300/10"}`}
                          onClick={() => completeTask(task.id, task.link)}
                          disabled={task.completed || loadingTask === task.id}
                          aria-label={task.completed ? `${task.title} completed` : `Complete ${task.title}`}
                        >
                          {loadingTask === task.id ? <FaSpinner className="animate-spin" /> : task.completed ? <MdTaskAlt /> : <FaArrowRight />}
                        </button>
                      </motion.div>
                    ))}
                  </div>

                  <div className="mt-6">
                    <div className="mb-2.5 flex items-center justify-between text-xs">
                      <span className="font-medium text-slate-400">Tasks completed</span>
                      <span className="font-bold tabular-nums text-violet-200">{completedTasks} / {tasks.length}</span>
                    </div>
                    <div className="h-2 overflow-hidden rounded-full bg-white/[0.06]">
                      <motion.div
                        className="h-full rounded-full bg-gradient-to-r from-violet-500 via-indigo-400 to-cyan-300 shadow-[0_0_16px_rgba(115,94,245,.5)]"
                        initial={false}
                        animate={{ width: `${progress}%` }}
                        transition={{ duration: 0.45, ease: "easeOut" }}
                      />
                    </div>
                    {!allTasksCompleted && <p className="mt-2 text-xs text-slate-500">Complete every task to unlock minting.</p>}
                  </div>
                </>
              ) : (
                <div className="rounded-2xl border border-cyan-300/15 bg-cyan-300/[0.04] p-4 text-sm text-slate-300">
                  This collection has no required tasks. Connect your wallet to mint.
                </div>
              )}

              <div className="mt-6 border-t border-white/[0.07] pt-5">
                {activeAccount ? (
                  <div className="flex flex-col gap-3 sm:flex-row">
                    <div className="flex shrink-0 items-center justify-between gap-4 rounded-2xl border border-white/[0.08] bg-white/[0.025] px-3 py-2 sm:w-[154px]">
                      <button type="button" aria-label="Decrease mint quantity" disabled={quantity <= 1} onClick={() => setQuantity((current) => Math.max(1, current - 1))} className="flex h-9 w-9 items-center justify-center rounded-xl text-slate-300 transition hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-35">
                        <FaMinusCircle />
                      </button>
                      <span className="min-w-5 text-center text-base font-bold tabular-nums text-white">{quantity}</span>
                      <button type="button" aria-label="Increase mint quantity" onClick={() => setQuantity((current) => current + 1)} className="flex h-9 w-9 items-center justify-center rounded-xl text-cyan-200 transition hover:bg-cyan-300/10">
                        <FaPlusCircle />
                      </button>
                    </div>
                    <ClaimButton
                      disabled={mintPending || (tasks.length > 0 && !allTasksCompleted)}
                      onClick={() => {
                        setMintError("");
                        setMintTxHash("");
                        setMintPending(true);
                        setMintStatus("Confirm the transaction in your wallet...");
                      }}
                      onTransactionSent={(result) => {
                        setMintTxHash(result.transactionHash);
                        setMintStatus("Transaction submitted. Waiting for confirmation...");
                      }}
                      onTransactionConfirmed={(receipt) => {
                        setMintPending(false);
                        setMintTxHash(receipt.transactionHash);
                        setMintStatus("Mint confirmed successfully.");
                      }}
                      onError={(error) => {
                        setMintPending(false);
                        setMintStatus("");
                        setMintError(error?.message || "The mint transaction could not be completed.");
                      }}
                      contractAddress={nft.address}
                      chain={chain}
                      client={client}
                      className="min-h-[54px] flex-1 rounded-2xl border border-violet-200/20 bg-gradient-to-r from-violet-600 via-indigo-600 to-blue-600 px-6 py-3 text-sm font-bold text-white shadow-[0_12px_35px_rgba(83,64,220,.25)] transition hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-45 disabled:shadow-none"
                      claimParams={{ type: "ERC721", quantity: BigInt(quantity) }}
                    >
                      {mintPending ? (mintStatus.startsWith("Transaction") ? "Waiting for confirmation..." : "Confirm in wallet...") : `Mint ${quantity > 1 ? `${quantity} NFTs` : "NFT"}`}
                    </ClaimButton>
                  </div>
                ) : (
                  <div className="rounded-2xl border border-white/[0.07] bg-white/[0.025] p-4">
                    <ThirdConnect />
                    <p className="mt-3 text-center text-xs text-slate-500">Connect your wallet to continue with the claim.</p>
                  </div>
                )}
                {(mintError || mintStatus) && (
                  <div
                    role={mintError ? "alert" : "status"}
                    aria-live="polite"
                    className={`mt-3 rounded-xl border px-4 py-3 text-xs leading-5 ${mintError ? "border-rose-300/20 bg-rose-400/[0.06] text-rose-200" : "border-cyan-300/15 bg-cyan-300/[0.04] text-cyan-100"}`}
                  >
                    <p>{mintError || mintStatus}</p>
                    {mintTxHash && nft.explorerLink && (
                      <a
                        href={`${new URL(nft.explorerLink).origin}/tx/${mintTxHash}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="mt-1 inline-flex font-semibold underline underline-offset-2 hover:text-white"
                      >
                        View transaction
                      </a>
                    )}
                  </div>
                )}
              </div>
            </motion.div>
          </section>
        )}
      </main>

      <div className="relative z-10 mt-8 w-full"><Footer /></div>
    </div>
  );
};

export default NFTCheckout;
