"use client";

import { useRouter } from "next/navigation";
import { useState, useEffect, useCallback, use } from "react";
import {
  Loader2,
  Home,
  ArrowLeft,
  Database,
  Activity,
  Lightbulb,
} from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";

export default function LoadingPage(props: {
  params: Promise<{ slug: string }>;
}) {
  const params = use(props.params);
  const portfolioId = params.slug;
  const router = useRouter();
  const [countdown, setCountdown] = useState(10);
  const [stageIndex, setStageIndex] = useState(0);

  const stages = [
    {
      icon: <Database className="w-14 h-14 text-white/90" />,
      title: "Gathering Data",
      text: "Collecting EPC, property, and mapping data from trusted sources.",
    },
    {
      icon: <Activity className="w-14 h-14 text-white/90" />,
      title: "Analysing Models",
      text: "Running retrofit simulations to identify the most effective measures.",
    },
    {
      icon: <Lightbulb className="w-14 h-14 text-white/90" />,
      title: "Generating Plan",
      text: "Assembling your detailed retrofit plan and funding summary.",
    },
  ];

  const handleBackToPortfolio = useCallback(() => {
    router.push(portfolioId ? `/portfolio/${portfolioId}` : "/home");
  }, [portfolioId, router]);

  useEffect(() => {
    if (countdown === 0) {
      handleBackToPortfolio();
      return;
    }
    const timer = setInterval(() => setCountdown((prev) => prev - 1), 1000);
    return () => clearInterval(timer);
  }, [countdown, handleBackToPortfolio]);

  useEffect(() => {
    const timer = setInterval(() => {
      setStageIndex((prev) => (prev + 1) % stages.length);
    }, 4000);
    return () => clearInterval(timer);
  }, [stages.length]);

  return (
    <div className="relative flex flex-col md:flex-row min-h-screen bg-gray-50 overflow-hidden">
      {/* LEFT PANEL – Centered Blueprint */}
      <div className="hidden md:flex w-1/2 relative items-center justify-center overflow-hidden">
        <div
          className="absolute inset-0 bg-cover bg-center"
          style={{ backgroundImage: "url('/images/Alexandra-Road-Park.webp')" }}
        />
        <div className="absolute inset-0 bg-gradient-to-r from-brandblue/95 to-midblue/85" />

        {/* Animated grid overlay */}
        <svg
          className="absolute inset-0 w-full h-full opacity-20"
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 800 600"
        >
          <g stroke="white" strokeWidth="0.4">
            {[...Array(20)].map((_, i) => (
              <line
                key={`v-${i}`}
                x1={(i + 1) * 40}
                y1="0"
                x2={(i + 1) * 40}
                y2="600"
                className="animate-[pulse_6s_ease-in-out_infinite]"
              />
            ))}
            {[...Array(15)].map((_, i) => (
              <line
                key={`h-${i}`}
                y1={(i + 1) * 40}
                x1="0"
                y2={(i + 1) * 40}
                x2="800"
                className="animate-[pulse_8s_ease-in-out_infinite]"
              />
            ))}
          </g>
        </svg>

        {/* Centered analysis stage */}
        <div className="relative z-10 flex flex-col items-center justify-center text-center text-white px-8">
          <AnimatePresence mode="wait">
            <motion.div
              key={stages[stageIndex].title}
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -30 }}
              transition={{ duration: 0.6 }}
              className="flex flex-col items-center"
            >
              <div className="mb-5">{stages[stageIndex].icon}</div>
              <h2 className="text-4xl font-bold mb-3">
                {stages[stageIndex].title}
              </h2>
              <p className="text-lg text-white/80 max-w-sm leading-relaxed">
                {stages[stageIndex].text}
              </p>
            </motion.div>
          </AnimatePresence>
        </div>
      </div>

      {/* RIGHT PANEL – Glass Card */}
      <div className="flex flex-1 flex-col justify-center items-center p-8 bg-gradient-to-b from-white to-sky-50 relative">
        <div className="absolute top-0 left-0 w-64 h-64 bg-brandbrown/10 rounded-full blur-3xl -translate-x-24 -translate-y-24 animate-pulse" />
        <div className="absolute bottom-0 right-0 w-80 h-80 bg-brandblue/10 rounded-full blur-3xl translate-x-20 translate-y-20 animate-[pulse_4s_ease-in-out_infinite]" />

        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
          className="relative z-10 bg-white/80 backdrop-blur-md border border-gray-100 shadow-2xl rounded-3xl px-10 py-12 text-center max-w-lg"
        >
          <div className="flex justify-center mb-6">
            <div className="relative">
              <Loader2 className="w-12 h-12 text-brandblue animate-spin" />
              <Home className="absolute inset-0 w-5 h-5 text-brandbrown m-auto" />
            </div>
          </div>

          <h2 className="text-3xl font-semibold text-brandblue mb-3">
            Building your retrofit plan
          </h2>
          <p className="text-slate-600 mb-3 text-base">
            Ara is analysing your data and generating your plan summary.
          </p>

          <div className="relative w-full h-2 bg-gray-200 rounded-full overflow-hidden mb-6">
            <motion.div
              className="absolute top-0 left-0 h-full bg-brandbrown"
              animate={{ width: `${((10 - countdown) / 10) * 100}%` }}
              transition={{ ease: "easeInOut", duration: 1 }}
            />
          </div>

          <p className="text-slate-500 text-sm mb-6">
            Redirecting in{" "}
            <span className="font-semibold text-brandbrown">{countdown}</span>{" "}
            seconds...
          </p>

          <button
            onClick={handleBackToPortfolio}
            className="mt-3 px-5 py-3 bg-brandblue text-white rounded-xl hover:bg-hoverblue flex items-center gap-2 mx-auto transition-all shadow-sm"
          >
            <ArrowLeft className="w-5 h-5" />
            Go back to portfolio
          </button>
        </motion.div>

        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.6 }}
          className="relative z-10 mt-8 text-sm text-gray-500"
        >
          Your assessment is running securely in the background.
        </motion.div>
      </div>
    </div>
  );
}
