'use client'

import { useState, Suspense } from 'react'
import { useSearchParams } from 'next/navigation'
import Link from 'next/link'
import { motion, AnimatePresence } from 'framer-motion'
import { Lock, ShieldCheck, CreditCard, Check, ChevronRight, Loader2 } from 'lucide-react'
import PageTransition from '@/components/PageTransition'
import { services } from '@/lib/mock-data'
import { formatPrice } from '@/lib/utils'

// Confetti particle
function Particle({ i }: { i: number }) {
  const colors = ['#4f46e5', '#818cf8', '#34d399', '#fbbf24', '#f472b6', '#60a5fa']
  const color = colors[i % colors.length]
  const angle = (i / 12) * 360
  const distance = 80 + Math.random() * 60

  return (
    <motion.div
      className="absolute rounded-full pointer-events-none"
      style={{
        width: 8 + (i % 3) * 4,
        height: 8 + (i % 3) * 4,
        backgroundColor: color,
        top: '50%',
        left: '50%',
      }}
      initial={{ x: 0, y: 0, opacity: 1, scale: 0 }}
      animate={{
        x: Math.cos((angle * Math.PI) / 180) * distance,
        y: Math.sin((angle * Math.PI) / 180) * distance - 40,
        opacity: [1, 1, 0],
        scale: [0, 1, 0.5],
      }}
      transition={{ duration: 0.9, ease: 'easeOut', delay: i * 0.03 }}
    />
  )
}

function PaymentContent() {
  const searchParams = useSearchParams()
  const serviceId = searchParams.get('service') ?? 'box-standard'
  const date = searchParams.get('date') ?? '2026-04-17'
  const slot = searchParams.get('slot') ?? '14:00 - 15:00'

  const service = services.find((s) => s.id === serviceId) ?? services[0]

  const [paying, setPaying] = useState(false)
  const [success, setSuccess] = useState(false)
  const [showParticles, setShowParticles] = useState(false)

  const [cardNumber, setCardNumber] = useState('4242 4242 4242 4242')
  const [expiry, setExpiry] = useState('12/28')
  const [cvc, setCvc] = useState('123')
  const [name, setName] = useState('Jean Dupont')

  const dateFormatted = (() => {
    try {
      return new Date(date).toLocaleDateString('fr-FR', {
        weekday: 'long',
        day: 'numeric',
        month: 'long',
      })
    } catch {
      return date
    }
  })()

  function handlePay() {
    if (paying || success) return
    setPaying(true)
    setTimeout(() => {
      setPaying(false)
      setSuccess(true)
      setShowParticles(true)
      setTimeout(() => setShowParticles(false), 1200)
    }, 2000)
  }

  const inputClass =
    'w-full bg-white border border-gray-200 rounded-xl px-4 py-3 text-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition placeholder-gray-400'

  return (
    <div className="max-w-6xl mx-auto px-4 py-8">
      <h1 className="text-2xl font-bold text-gray-900 mb-8 text-center md:text-left">Paiement</h1>

      <div className="flex flex-col md:flex-row gap-6 items-start">
        {/* Order summary */}
        <div className="w-full md:w-80 md:flex-shrink-0 order-first md:order-last">
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
            <div className="bg-gradient-to-r from-brand-600 to-brand-700 px-5 py-4">
              <p className="text-white font-semibold">{service.name}</p>
              <p className="text-brand-100 text-sm capitalize">{dateFormatted}</p>
            </div>
            <div className="p-5 flex flex-col gap-3">
              <div className="flex justify-between text-sm">
                <span className="text-gray-500">Horaire</span>
                <span className="font-medium text-gray-900">{slot}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-500">Tarif</span>
                <span className="text-gray-900">{formatPrice(service.pricePerHour)}/h</span>
              </div>
              <div className="border-t border-gray-100 pt-3">
                <div className="flex justify-between">
                  <span className="text-gray-700 font-medium">Caution</span>
                  <span className="font-bold text-brand-600 text-base">{formatPrice(service.deposit)}</span>
                </div>
                <p className="text-xs text-gray-400 mt-1.5 leading-relaxed">
                  Montant final ajusté après utilisation.
                </p>
              </div>
              <div className="bg-gray-50 rounded-xl p-3 border-t border-gray-100">
                <div className="flex justify-between font-semibold">
                  <span className="text-gray-800">Total à payer</span>
                  <span className="text-brand-600 text-lg">{formatPrice(service.deposit)}</span>
                </div>
              </div>
              <p className="text-xs text-gray-400 leading-relaxed">
                Vous serez remboursé de la différence entre la caution et le coût réel de votre utilisation.
              </p>
            </div>
          </div>
        </div>

        {/* Payment form */}
        <div className="flex-1 w-full">
          <AnimatePresence mode="wait">
            {!success ? (
              <motion.div
                key="form"
                initial={{ opacity: 0, y: 16 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -16 }}
                transition={{ duration: 0.3 }}
                className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6"
              >
                <div className="flex items-center gap-2 mb-6">
                  <CreditCard className="w-5 h-5 text-brand-600" />
                  <h2 className="font-semibold text-gray-800">Informations de paiement</h2>
                </div>

                <div className="flex flex-col gap-4">
                  {/* Card number */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1.5">
                      Numéro de carte
                    </label>
                    <div className="relative">
                      <input
                        type="text"
                        value={cardNumber}
                        onChange={(e) => setCardNumber(e.target.value)}
                        className={inputClass + ' pr-12'}
                        placeholder="1234 5678 9012 3456"
                      />
                      <div className="absolute right-3 top-1/2 -translate-y-1/2 flex gap-1">
                        <div className="w-6 h-4 bg-yellow-400 rounded-sm opacity-80" />
                        <div className="w-6 h-4 bg-red-500 rounded-sm opacity-70 -ml-3" />
                      </div>
                    </div>
                  </div>

                  {/* Expiry + CVC */}
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1.5">
                        Date d'expiration
                      </label>
                      <input
                        type="text"
                        value={expiry}
                        onChange={(e) => setExpiry(e.target.value)}
                        className={inputClass}
                        placeholder="MM/AA"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1.5">
                        Code CVC
                      </label>
                      <input
                        type="text"
                        value={cvc}
                        onChange={(e) => setCvc(e.target.value)}
                        className={inputClass}
                        placeholder="123"
                      />
                    </div>
                  </div>

                  {/* Name */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1.5">
                      Nom du titulaire
                    </label>
                    <input
                      type="text"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      className={inputClass}
                      placeholder="Jean Dupont"
                    />
                  </div>
                </div>

                {/* Security badges */}
                <div className="flex items-center justify-center gap-4 mt-5 py-3 bg-gray-50 rounded-xl">
                  <div className="flex items-center gap-1.5 text-xs text-gray-500">
                    <Lock className="w-3.5 h-3.5 text-gray-400" />
                    Paiement sécurisé
                  </div>
                  <div className="w-px h-3 bg-gray-300" />
                  <div className="flex items-center gap-1.5 text-xs text-gray-500">
                    <ShieldCheck className="w-3.5 h-3.5 text-gray-400" />
                    Chiffrement SSL
                  </div>
                  <div className="w-px h-3 bg-gray-300" />
                  <span className="text-xs text-gray-400 font-semibold">256-bit</span>
                </div>

                {/* Pay button */}
                <motion.button
                  onClick={handlePay}
                  disabled={paying}
                  whileTap={!paying ? { scale: 0.97 } : {}}
                  whileHover={!paying ? { scale: 1.02 } : {}}
                  className={`w-full mt-5 py-4 rounded-xl font-semibold text-base transition-colors flex items-center justify-center gap-2 ${
                    paying
                      ? 'bg-brand-400 cursor-not-allowed text-white'
                      : 'bg-brand-600 hover:bg-brand-700 text-white'
                  }`}
                >
                  {paying ? (
                    <>
                      <Loader2 className="w-5 h-5 animate-spin" />
                      Traitement en cours...
                    </>
                  ) : (
                    <>
                      Payer {formatPrice(service.deposit)}
                      <ChevronRight className="w-5 h-5" />
                    </>
                  )}
                </motion.button>
              </motion.div>
            ) : (
              <motion.div
                key="success"
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ duration: 0.4, ease: [0.25, 0.1, 0.25, 1] }}
                className="bg-white rounded-2xl border border-gray-100 shadow-sm p-8 text-center relative overflow-hidden"
              >
                {/* Particles */}
                {showParticles && (
                  <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
                    {Array.from({ length: 14 }).map((_, i) => (
                      <Particle key={i} i={i} />
                    ))}
                  </div>
                )}

                {/* Checkmark */}
                <div className="flex justify-center mb-6">
                  <motion.div
                    initial={{ scale: 0 }}
                    animate={{ scale: 1 }}
                    transition={{ type: 'spring', stiffness: 300, damping: 20, delay: 0.1 }}
                    className="w-20 h-20 rounded-full bg-success-50 border-4 border-success-400 flex items-center justify-center"
                  >
                    <motion.div
                      initial={{ opacity: 0, scale: 0 }}
                      animate={{ opacity: 1, scale: 1 }}
                      transition={{ delay: 0.3, duration: 0.3 }}
                    >
                      <Check className="w-9 h-9 text-success-500" strokeWidth={3} />
                    </motion.div>
                  </motion.div>
                </div>

                <motion.h2
                  initial={{ opacity: 0, y: 12 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.35 }}
                  className="text-2xl font-bold text-gray-900 mb-2"
                >
                  Paiement confirmé !
                </motion.h2>
                <motion.p
                  initial={{ opacity: 0, y: 8 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.45 }}
                  className="text-gray-500 mb-6"
                >
                  Votre accès a été généré
                </motion.p>

                {/* PIN display */}
                <motion.div
                  initial={{ opacity: 0, y: 12 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.55 }}
                  className="bg-brand-50 rounded-2xl p-6 mb-6 border-2 border-brand-100"
                >
                  <p className="text-sm text-brand-600 font-medium mb-2">Votre code PIN d'accès</p>
                  <div className="flex items-center justify-center gap-3">
                    {['6', '2', '4', '7'].map((digit, i) => (
                      <motion.div
                        key={i}
                        initial={{ opacity: 0, y: 8, scale: 0.8 }}
                        animate={{ opacity: 1, y: 0, scale: 1 }}
                        transition={{ delay: 0.65 + i * 0.07 }}
                        className="w-14 h-16 bg-white rounded-xl border-2 border-brand-200 flex items-center justify-center text-3xl font-bold text-brand-700 shadow-sm"
                      >
                        {digit}
                      </motion.div>
                    ))}
                  </div>
                  <p className="text-xs text-brand-400 mt-3">
                    Présentez ce code à l'entrée de votre espace
                  </p>
                </motion.div>

                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ delay: 0.9 }}
                >
                  <Link href="/acces">
                    <motion.span
                      whileHover={{ scale: 1.03 }}
                      whileTap={{ scale: 0.97 }}
                      className="inline-flex items-center gap-2 bg-brand-600 text-white font-semibold px-7 py-3.5 rounded-xl cursor-pointer select-none"
                    >
                      Voir mon accès
                      <ChevronRight className="w-5 h-5" />
                    </motion.span>
                  </Link>
                </motion.div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>
    </div>
  )
}

export default function PaiementPage() {
  return (
    <PageTransition>
      <Suspense fallback={<div className="flex items-center justify-center min-h-[60vh] text-gray-400">Chargement...</div>}>
        <PaymentContent />
      </Suspense>
    </PageTransition>
  )
}
