"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { FaShoppingBag, FaArrowRight, FaHome } from "react-icons/fa";

export default function CheckoutSuccessPage() {
  const [showConfetti, setShowConfetti] = useState(false);

  useEffect(() => {
    // Trigger confetti trigger state
    setShowConfetti(true);

    // Play PhonePe-like premium payment double-chime using Web Audio API
    try {
      const AudioContext = window.AudioContext || (window as any).webkitAudioContext;
      if (AudioContext) {
        const ctx = new AudioContext();
        const playTone = (freq: number, start: number, duration: number, volume: number = 0.15) => {
          const osc = ctx.createOscillator();
          const gain = ctx.createGain();
          
          osc.type = "sine";
          osc.frequency.setValueAtTime(freq, start);
          
          gain.gain.setValueAtTime(volume, start);
          gain.gain.exponentialRampToValueAtTime(0.0001, start + duration);
          
          osc.connect(gain);
          gain.connect(ctx.destination);
          
          osc.start(start);
          osc.stop(start + duration);
        };

        const now = ctx.currentTime;
        // Harmonious, bright chord progression: C5 -> E5 -> G5 -> C6
        playTone(523.25, now + 0.15, 0.35, 0.12);
        playTone(659.25, now + 0.25, 0.35, 0.12);
        playTone(783.99, now + 0.35, 0.45, 0.15);
        playTone(1046.50, now + 0.48, 0.65, 0.15);
      }
    } catch (e) {
      console.warn("Failed to play audio chime", e);
    }
  }, []);

  return (
    <div className="min-h-[85vh] flex items-center justify-center bg-[#FAF9F6] px-4 py-12 relative overflow-hidden select-none">
      
      {/* Dynamic CSS Keyframe animations */}
      <style>{`
        @keyframes strokeCheck {
          100% {
            stroke-dashoffset: 0;
          }
        }
        @keyframes scaleCheckCircle {
          0%, 100% {
            transform: scale(1);
          }
          50% {
            transform: scale(1.08);
          }
        }
        @keyframes fillCheckCircle {
          100% {
            fill: #10B981;
          }
        }
        @keyframes growRipple {
          0% {
            transform: translate(-50%, -50%) scale(0.6);
            opacity: 0.8;
          }
          100% {
            transform: translate(-50%, -50%) scale(1.6);
            opacity: 0;
          }
        }
        @keyframes fallConfetti {
          0% {
            transform: translateY(-50px) rotate(0deg);
            opacity: 1;
          }
          100% {
            transform: translateY(100vh) rotate(360deg);
            opacity: 0.3;
          }
        }
        .animate-check-stroke {
          stroke-dasharray: 48;
          stroke-dashoffset: 48;
          animation: strokeCheck 0.35s cubic-bezier(0.65, 0, 0.45, 1) 0.6s forwards;
        }
        .animate-circle-stroke {
          stroke-dasharray: 157;
          stroke-dashoffset: 157;
          animation: 
            strokeCheck 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards,
            fillCheckCircle 0.3s ease-in-out 0.5s forwards,
            scaleCheckCircle 0.4s ease-in-out 0.8s;
        }
      `}</style>

      {/* Confetti Elements */}
      {showConfetti && (
        <div className="absolute inset-0 pointer-events-none z-0">
          {[...Array(40)].map((_, i) => {
            const colors = ["#10B981", "#3B82F6", "#F59E0B", "#EF4444", "#EC4899", "#8B5CF6"];
            const color = colors[i % colors.length];
            const size = Math.random() * 8 + 6;
            const left = Math.random() * 100;
            const delay = Math.random() * 3;
            const duration = Math.random() * 2 + 3;
            return (
              <div
                key={i}
                className="absolute"
                style={{
                  top: "-5%",
                  left: `${left}%`,
                  width: `${size}px`,
                  height: `${size}px`,
                  backgroundColor: color,
                  borderRadius: i % 2 === 0 ? "50%" : "2px",
                  animation: `fallConfetti ${duration}s linear ${delay}s infinite`,
                }}
              />
            );
          })}
        </div>
      )}

      {/* Main Card */}
      <div 
        style={{ animation: "slideUp 0.8s cubic-bezier(0.16, 1, 0.3, 1) both" }}
        className="max-w-xl w-full bg-white rounded-[2.5rem] border border-gray-200/60 shadow-[0_15px_50px_rgba(0,0,0,0.03)] p-8 sm:p-12 text-center relative overflow-hidden z-10"
      >
        {/* PhonePe Green/Emerald Top Strip */}
        <div className="absolute top-0 left-0 right-0 h-1.5 bg-gradient-to-r from-emerald-400 to-emerald-600" />
        
        {/* PhonePe Pulsing Green Success Checkmark */}
        <div className="flex justify-center mb-8 relative">
          
          {/* Wave/Ripple rings */}
          <div 
            style={{ animation: "growRipple 2.2s cubic-bezier(0.1, 0.8, 0.3, 1) 0.5s infinite" }}
            className="absolute top-1/2 left-1/2 w-36 h-36 border-2 border-emerald-400/40 rounded-full pointer-events-none select-none z-0" 
          />
          <div 
            style={{ animation: "growRipple 2.2s cubic-bezier(0.1, 0.8, 0.3, 1) 1.2s infinite" }}
            className="absolute top-1/2 left-1/2 w-36 h-36 border-2 border-emerald-400/20 rounded-full pointer-events-none select-none z-0" 
          />
          
          {/* Animated SVG Check Circle */}
          <svg className="w-24 h-24 relative z-10" viewBox="0 0 52 52">
            <circle 
              className="animate-circle-stroke stroke-emerald-500 fill-none" 
              cx="26" cy="26" r="25" 
              strokeWidth="4" 
            />
            <path 
              className="animate-check-stroke stroke-white fill-none" 
              d="M14 27l8 8 16-16" 
              strokeWidth="4.5" 
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </div>
        
        <h1 className="text-3xl font-black text-gray-900 mb-2 tracking-tight">Order Placed Successfully!</h1>
        <p className="text-gray-500 font-bold text-xs uppercase tracking-wider mb-6">
          Payment confirmed • Thank you for your purchase
        </p>
        
        <p className="text-sm text-gray-550 mb-8 leading-relaxed font-semibold max-w-md mx-auto">
          We&apos;ve successfully registered your order. Our warehouse team has been notified and is beginning packaging and dispatch procedures immediately.
        </p>

        {/* Order workflow guide */}
        <div className="bg-emerald-50/40 border border-emerald-100/50 rounded-2.5xl p-6 mb-8 text-left">
          <h3 className="font-extrabold text-sm text-emerald-800 mb-3 flex items-center gap-2">
            <FaShoppingBag className="text-emerald-600" /> Order Operations Workflow
          </h3>
          <ul className="text-xs text-emerald-700/90 space-y-2.5 font-bold list-disc list-inside">
            <li>An invoice and order summary has been emailed to you.</li>
            <li>Tracking credentials will be updated in your ledger within 24 hours.</li>
            <li>You can download the PDF PO from the Order Detail dashboard.</li>
          </ul>
        </div>

        {/* Navigation Actions */}
        <div className="flex flex-col sm:flex-row gap-4 justify-center">
          <Link 
            href="/profile/order" 
            className="flex-1 inline-flex items-center justify-center gap-2 px-6 py-4 text-xs font-black uppercase tracking-wider bg-slate-900 hover:bg-slate-800 text-white rounded-2xl shadow-md active:scale-95 transition-all"
          >
            View Order History <FaArrowRight className="text-[10px]" />
          </Link>
          <Link 
            href="/" 
            className="flex-1 inline-flex items-center justify-center gap-2 px-6 py-4 text-xs font-black uppercase tracking-wider rounded-2xl bg-gray-105 hover:bg-gray-200 text-gray-700 active:scale-95 transition-all border border-gray-200/50"
          >
            <FaHome /> Shop Home
          </Link>
        </div>
      </div>
    </div>
  );
}
