"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ArrowRight, CheckCircle2, FileText } from "lucide-react";

import { Button } from "@/components/ui/button";
import { useAuthStore } from "@/stores/auth-store";
import { useReportStore } from "@/stores/report-store";

export default function CheckoutSuccessPage() {
  const router = useRouter();
  const { currentReport, reports, loadReports } = useReportStore();
  const { user } = useAuthStore();
  const [countdown, setCountdown] = useState(3);

  // Ensure reports are loaded so we can show the accurate count
  useEffect(() => {
    if (user?.id) loadReports(user.id);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.id]);

  useEffect(() => {
    if (countdown <= 0) {
      router.push("/dashboard/reports");
      return;
    }
    const timer = setTimeout(() => setCountdown((c) => c - 1), 1000);
    return () => clearTimeout(timer);
  }, [countdown, router]);

  const packageName = currentReport
    ? currentReport.tier.charAt(0).toUpperCase() + currentReport.tier.slice(1)
    : "Report";

  const reportCount = reports.length;

  return (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center px-4 overflow-hidden relative">
      {/* CSS confetti animation */}
      <style>{`
        @keyframes confetti-fall {
          0% { transform: translateY(-100px) rotate(0deg); opacity: 1; }
          100% { transform: translateY(110vh) rotate(720deg); opacity: 0; }
        }
        .confetti-piece {
          position: fixed;
          top: -20px;
          animation: confetti-fall linear forwards;
          pointer-events: none;
          z-index: 0;
        }
      `}</style>

      {/* Confetti pieces */}
      {Array.from({ length: 30 }).map((_, i) => {
        const colors = ["#0F766E", "#D97706", "#7C3AED", "#DB2777", "#059669", "#1D4ED8"];
        const color = colors[i % colors.length];
        const left = `${(i * 3.5) % 100}%`;
        const delay = `${(i * 0.15) % 3}s`;
        const duration = `${2.5 + (i % 5) * 0.3}s`;
        const size = `${8 + (i % 4) * 3}px`;
        const shape = i % 3 === 0 ? "50%" : i % 3 === 1 ? "2px" : "0%";
        return (
          <div
            key={i}
            className="confetti-piece"
            style={{
              left,
              animationDelay: delay,
              animationDuration: duration,
              width: size,
              height: size,
              backgroundColor: color,
              borderRadius: shape,
            }}
          />
        );
      })}

      {/* Main content */}
      <div className="relative z-10 bg-white rounded-3xl border border-gray-100 shadow-2xl p-8 sm:p-12 max-w-md w-full text-center">
        {/* Checkmark */}
        <div className="flex justify-center mb-6">
          <div className="relative">
            <div className="w-20 h-20 rounded-full bg-green-100 flex items-center justify-center animate-[scale-in_0.5s_ease-out]">
              <CheckCircle2 className="w-10 h-10 text-green-600" strokeWidth={1.5} />
            </div>
            {/* Pulse rings */}
            <div className="absolute inset-0 rounded-full bg-green-200/50 animate-ping" />
          </div>
        </div>

        <h1 className="text-3xl font-extrabold text-gray-900 mb-2">Payment Successful!</h1>
        <p className="text-gray-500 mb-4 leading-relaxed">
          Your personalised{" "}
          <span className="font-semibold text-teal-700">{packageName}</span> report has been
          unlocked and added to your account.
        </p>

        {/* Report count confirmation */}
        {reportCount > 0 && (
          <div className="flex items-center justify-center gap-2 rounded-xl bg-green-50 border border-green-100 px-4 py-3 mb-4">
            <FileText className="h-4 w-4 text-green-600 shrink-0" />
            <p className="text-sm font-semibold text-green-700">
              1 new report added · {reportCount} total report{reportCount !== 1 ? "s" : ""} in My Reports
            </p>
          </div>
        )}

        {/* Countdown */}
        <div className="rounded-xl bg-teal-50 border border-teal-100 px-5 py-4 mb-6">
          <p className="text-sm text-teal-700 font-medium">
            Viewing your report in{" "}
            <span className="text-2xl font-extrabold text-teal-600 tabular-nums">
              {countdown}
            </span>
            {countdown > 0 ? "..." : ""}
          </p>
          <div className="mt-2 h-1.5 bg-teal-200 rounded-full overflow-hidden">
            <div
              className="h-full bg-teal-600 rounded-full transition-all duration-1000"
              style={{ width: `${((3 - countdown) / 3) * 100}%` }}
            />
          </div>
        </div>

        <Button
          onClick={() => router.push("/dashboard/reports")}
          className="w-full bg-teal-600 hover:bg-teal-700 text-white font-bold py-3 rounded-xl shadow-md hover:shadow-lg transition-all group"
        >
          View My Report Now
          <ArrowRight className="ml-2 h-4 w-4 group-hover:translate-x-0.5 transition-transform" />
        </Button>

        <p className="text-xs text-gray-400 mt-4">
          A confirmation has been sent to your email address.
        </p>
      </div>
    </div>
  );
}
