'use client'

import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { KeyRound, Copy, Check, Clock, Shield, HelpCircle, LogOut } from 'lucide-react'
import { useRouter } from 'next/navigation'
import { QRCodeSVG } from 'qrcode.react'
import PageTransition, { StaggerContainer, StaggerItem } from '@/components/PageTransition'
import { activeReservation } from '@/lib/mock-data'
import { formatPrice } from '@/lib/utils'

export default function AccesPage() {
  const [copied, setCopied] = useState(false)
  const router = useRouter()

  const hasActive = !!activeReservation

  const handleCopy = () => {
    navigator.clipboard.writeText(activeReservation?.pin ?? '').catch(() => {})
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  if (!hasActive) {
    return (
      <PageTransition>
        <div className="max-w-2xl mx-auto px-4 py-8 flex flex-col items-center justify-center min-h-[70vh] text-center gap-6">
          <div className="w-24 h-24 rounded-full bg-gray-100 flex items-center justify-center">
            <KeyRound className="w-12 h-12 text-gray-300" />
          </div>
          <div>
            <h2 className="text-xl font-bold text-gray-800 mb-2">Aucun accès actif</h2>
            <p className="text-gray-500 text-sm">Réservez un espace pour obtenir votre accès</p>
          </div>
          <motion.button
            whileTap={{ scale: 0.97 }}
            onClick={() => router.push('/reserver')}
            className="bg-indigo-600 text-white px-6 py-3 rounded-xl font-semibold"
          >
            Réserver un espace
          </motion.button>
        </div>
      </PageTransition>
    )
  }

  const res = activeReservation
  const [startHour] = res.timeSlot.split(' - ')
  const [, endHour] = res.timeSlot.split(' - ')
  const now = new Date()
  const today = res.date
  const startDateTime = new Date(`${today}T${startHour}:00`)
  const endDateTime = new Date(`${today}T${endHour}:00`)
  const totalMinutes = (endDateTime.getTime() - now.getTime()) / 60000
  const remainingMinutes = Math.max(0, Math.floor(totalMinutes))
  const remainingH = Math.floor(remainingMinutes / 60)
  const remainingM = remainingMinutes % 60
  const remainingStr =
    remainingH > 0
      ? `${remainingH}h ${String(remainingM).padStart(2, '0')}min`
      : `${remainingM}min`

  const qrValue = `smartacces://access/${res.id}/${res.pin}`
  const pinDigits = res.pin.split('')

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

  return (
    <PageTransition>
      <div className="max-w-2xl mx-auto px-4 py-6 space-y-5">

        {/* Header */}
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-indigo-100 flex items-center justify-center">
            <KeyRound className="w-5 h-5 text-indigo-600" />
          </div>
          <h1 className="text-2xl font-bold text-gray-900">Mon accès</h1>
        </div>

        {/* Active access card */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.05 }}
          className="bg-white rounded-2xl p-4 shadow-sm border border-gray-100"
        >
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <span className="relative flex h-2.5 w-2.5">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75" />
                <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-green-500" />
              </span>
              <span className="text-sm font-semibold text-green-600">Session active</span>
            </div>
            <span className="text-xs text-gray-400 bg-gray-50 px-2 py-1 rounded-lg">{res.id}</span>
          </div>
          <p className="font-bold text-gray-900">{res.serviceName}</p>
          <p className="text-sm text-gray-500 capitalize">{dateFormatted} · {res.timeSlot}</p>
        </motion.div>

        {/* PIN Code */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="bg-gradient-to-br from-indigo-600 to-indigo-700 rounded-2xl p-6 text-center shadow-lg"
        >
          <p className="text-indigo-200 text-sm font-medium mb-4">Code PIN d'accès</p>

          {/* PIN digits */}
          <div className="pulse-glow flex justify-center gap-3 mb-4">
            {pinDigits.map((digit, i) => (
              <motion.div
                key={i}
                initial={{ opacity: 0, scale: 0.5 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{
                  delay: 0.15 + i * 0.08,
                  type: 'spring',
                  stiffness: 300,
                  damping: 20,
                }}
                className="w-16 h-20 bg-white/20 backdrop-blur rounded-xl flex items-center justify-center border border-white/30"
              >
                <span className="text-5xl font-mono font-bold text-white">{digit}</span>
              </motion.div>
            ))}
          </div>

          <p className="text-indigo-200 text-xs mb-4">Présentez ce code à l'entrée</p>

          {/* Copy button */}
          <motion.button
            whileTap={{ scale: 0.97 }}
            onClick={handleCopy}
            className="flex items-center gap-2 mx-auto bg-white/20 hover:bg-white/30 transition-colors text-white px-5 py-2.5 rounded-xl text-sm font-medium border border-white/30"
          >
            <AnimatePresence mode="wait">
              {copied ? (
                <motion.span
                  key="check"
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.8 }}
                  className="flex items-center gap-2"
                >
                  <Check className="w-4 h-4" />
                  Copié !
                </motion.span>
              ) : (
                <motion.span
                  key="copy"
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.8 }}
                  className="flex items-center gap-2"
                >
                  <Copy className="w-4 h-4" />
                  Copier le code
                </motion.span>
              )}
            </AnimatePresence>
          </motion.button>
        </motion.div>

        {/* QR Code */}
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ delay: 0.2, duration: 0.4 }}
          className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100 flex flex-col items-center gap-3"
        >
          <div className="bg-white p-3 rounded-xl border border-gray-100 shadow-sm">
            <QRCodeSVG
              value={qrValue}
              size={180}
              level="M"
              includeMargin={false}
              fgColor="#312e81"
            />
          </div>
          <p className="text-sm text-gray-500 text-center">Scannez le QR code à la borne</p>
        </motion.div>

        {/* Session info */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.25 }}
          className="bg-white rounded-2xl p-4 shadow-sm border border-gray-100"
        >
          <div className="flex items-center gap-2 mb-3">
            <Clock className="w-4 h-4 text-indigo-500" />
            <span className="text-sm font-semibold text-gray-700">Informations de session</span>
          </div>
          <div className="space-y-2">
            {[
              { label: 'Début', value: startHour },
              { label: 'Fin prévue', value: endHour },
              { label: 'Temps restant', value: remainingStr, highlight: true },
              { label: 'Caution versée', value: formatPrice(res.deposit) },
            ].map(({ label, value, highlight }) => (
              <div key={label} className="flex justify-between items-center">
                <span className="text-sm text-gray-500">{label}</span>
                <span className={`text-sm font-semibold ${highlight ? 'text-indigo-600' : 'text-gray-800'}`}>
                  {value}
                </span>
              </div>
            ))}
          </div>
        </motion.div>

        {/* Action buttons */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="space-y-3 pb-4"
        >
          <motion.button
            whileTap={{ scale: 0.97 }}
            onClick={() => router.push('/session')}
            className="w-full bg-red-500 hover:bg-red-600 transition-colors text-white py-4 rounded-xl font-semibold flex items-center justify-center gap-2"
          >
            <LogOut className="w-4 h-4" />
            Terminer la session
          </motion.button>
          <motion.button
            whileTap={{ scale: 0.97 }}
            onClick={() => {}}
            className="w-full border border-gray-200 bg-white text-gray-700 py-4 rounded-xl font-semibold flex items-center justify-center gap-2"
          >
            <HelpCircle className="w-4 h-4" />
            Besoin d'aide ?
          </motion.button>
        </motion.div>

      </div>
    </PageTransition>
  )
}
