'use client'

import { useState, useMemo } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import {
  CheckCircle,
  ArrowDownLeft,
  CalendarDays,
  Timer,
  CreditCard,
  PlusCircle,
  Home,
} from 'lucide-react'
import { useRouter } from 'next/navigation'
import PageTransition, { StaggerContainer, StaggerItem } from '@/components/PageTransition'
import { activeReservation, services } from '@/lib/mock-data'
import { formatPrice, formatDuration } from '@/lib/utils'
import { useTimer } from '@/hooks/useTimer'

// Start ~45 min ago
const SESSION_START = new Date(Date.now() - 45 * 60 * 1000)
const MAX_DURATION_SECONDS = 8 * 3600 // 8h fallback

function pad(n: number) {
  return String(n).padStart(2, '0')
}

function formatElapsed(seconds: number) {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = seconds % 60
  return `${pad(h)}:${pad(m)}:${pad(s)}`
}

export default function SessionPage() {
  const [mode, setMode] = useState<'active' | 'ending' | 'ended'>('active')
  const router = useRouter()
  const elapsed = useTimer(SESSION_START)

  const service = useMemo(
    () => services.find((s) => s.id === activeReservation?.serviceId),
    []
  )

  const maxDurationSeconds = (service?.maxDuration ?? MAX_DURATION_SECONDS / 60) * 60
  const pricePerSecond = (service?.pricePerHour ?? 500) / 3600 / 100 // €/s
  const currentCostCents = Math.floor(elapsed * (service?.pricePerHour ?? 500) / 3600)
  const deposit = activeReservation?.deposit ?? 3500
  const refund = Math.max(0, deposit - currentCostCents)

  const progress = Math.min(1, elapsed / maxDurationSeconds)
  const circleR = 88
  const circleCircumference = 2 * Math.PI * circleR
  const strokeDashoffset = circleCircumference * (1 - progress)

  const handleEnd = () => {
    setMode('ending')
    setTimeout(() => setMode('ended'), 1500)
  }

  return (
    <PageTransition>
      <div className="max-w-2xl mx-auto px-4 py-6">
        <AnimatePresence mode="wait">

          {/* ACTIVE MODE */}
          {(mode === 'active' || mode === 'ending') && (
            <motion.div
              key="active"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              transition={{ duration: 0.3 }}
              className="space-y-5"
            >
              {/* Header */}
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-orange-100 flex items-center justify-center">
                  <Timer className="w-5 h-5 text-orange-600" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-gray-900">Session en cours</h1>
                  <p className="text-sm text-gray-500">{activeReservation?.serviceName}</p>
                </div>
              </div>

              {/* Timer circle */}
              <div className="bg-gradient-to-br from-indigo-600 to-indigo-800 rounded-2xl p-8 flex flex-col items-center shadow-lg">
                <div className="relative flex items-center justify-center w-52 h-52">
                  {/* SVG circular progress */}
                  <svg
                    className="absolute inset-0 w-full h-full -rotate-90"
                    viewBox="0 0 200 200"
                  >
                    <circle
                      cx="100"
                      cy="100"
                      r={circleR}
                      fill="none"
                      stroke="rgba(255,255,255,0.1)"
                      strokeWidth="8"
                    />
                    <motion.circle
                      cx="100"
                      cy="100"
                      r={circleR}
                      fill="none"
                      stroke="rgba(255,255,255,0.85)"
                      strokeWidth="8"
                      strokeLinecap="round"
                      strokeDasharray={circleCircumference}
                      strokeDashoffset={strokeDashoffset}
                      transition={{ duration: 0.8, ease: 'linear' }}
                    />
                  </svg>
                  {/* Timer text */}
                  <div className="text-center">
                    <span className="font-mono text-4xl font-bold text-white tracking-tight">
                      {formatElapsed(elapsed)}
                    </span>
                    <p className="text-indigo-200 text-xs mt-1">
                      max {service?.maxDuration ? `${service.maxDuration / 60}h` : '8h'}
                    </p>
                  </div>
                </div>

                {/* Progress bar */}
                <div className="w-full mt-4">
                  <div className="flex justify-between text-xs text-indigo-200 mb-1">
                    <span>0%</span>
                    <span>Temps utilisé : {Math.round(progress * 100)}%</span>
                    <span>100%</span>
                  </div>
                  <div className="w-full h-1.5 bg-white/20 rounded-full overflow-hidden">
                    <motion.div
                      className="h-full bg-white rounded-full"
                      style={{ width: `${progress * 100}%` }}
                    />
                  </div>
                </div>
              </div>

              {/* Live cost */}
              <motion.div
                className="bg-white rounded-2xl p-4 shadow-sm border border-gray-100 space-y-3"
              >
                <div className="flex items-center gap-2 mb-1">
                  <CreditCard className="w-4 h-4 text-indigo-500" />
                  <span className="text-sm font-semibold text-gray-700">Coût en temps réel</span>
                </div>
                {[
                  { label: 'Coût actuel', value: formatPrice(currentCostCents), cls: 'text-gray-900 font-bold text-lg' },
                  { label: 'Caution versée', value: formatPrice(deposit), cls: 'text-gray-700' },
                  {
                    label: 'Remboursement estimé',
                    value: formatPrice(refund),
                    cls: refund > 0 ? 'text-green-600 font-semibold' : 'text-red-500 font-semibold',
                  },
                ].map(({ label, value, cls }) => (
                  <div key={label} className="flex justify-between items-center">
                    <span className="text-sm text-gray-500">{label}</span>
                    <AnimatePresence mode="popLayout">
                      <motion.span
                        key={value}
                        initial={{ opacity: 0, y: -4 }}
                        animate={{ opacity: 1, y: 0 }}
                        className={`text-sm ${cls}`}
                      >
                        {value}
                      </motion.span>
                    </AnimatePresence>
                  </div>
                ))}
              </motion.div>

              {/* Session details */}
              <div className="bg-white rounded-2xl p-4 shadow-sm border border-gray-100">
                <div className="flex items-center gap-2 mb-3">
                  <CalendarDays className="w-4 h-4 text-indigo-500" />
                  <span className="text-sm font-semibold text-gray-700">Détails de la session</span>
                </div>
                <div className="space-y-2">
                  {[
                    { label: 'Service', value: activeReservation?.serviceName ?? '-' },
                    { label: 'Code PIN utilisé', value: activeReservation?.pin ?? '-' },
                    { label: 'Heure de début', value: activeReservation?.timeSlot.split(' - ')[0] ?? '-' },
                    { label: 'Durée écoulée', value: formatDuration(elapsed) },
                  ].map(({ label, value }) => (
                    <div key={label} className="flex justify-between">
                      <span className="text-sm text-gray-500">{label}</span>
                      <span className="text-sm font-medium text-gray-800">{value}</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* End button */}
              <motion.button
                whileTap={{ scale: 0.97 }}
                onClick={handleEnd}
                disabled={mode === 'ending'}
                className="w-full py-4 rounded-xl font-bold text-white text-base flex items-center justify-center gap-2 shadow-lg"
                style={{
                  background: 'linear-gradient(135deg, #f97316 0%, #ef4444 100%)',
                }}
              >
                {mode === 'ending' ? (
                  <motion.span
                    animate={{ opacity: [1, 0.4, 1] }}
                    transition={{ repeat: Infinity, duration: 0.8 }}
                  >
                    Fermeture en cours…
                  </motion.span>
                ) : (
                  'Terminer la session'
                )}
              </motion.button>
            </motion.div>
          )}

          {/* ENDED MODE */}
          {mode === 'ended' && (
            <motion.div
              key="ended"
              initial={{ opacity: 0, scale: 0.92 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.4, type: 'spring', stiffness: 200, damping: 22 }}
              className="space-y-6"
            >
              {/* Big checkmark */}
              <div className="flex flex-col items-center pt-6 pb-2">
                <motion.div
                  initial={{ scale: 0, opacity: 0 }}
                  animate={{ scale: 1, opacity: 1 }}
                  transition={{ type: 'spring', stiffness: 260, damping: 20, delay: 0.1 }}
                  className="w-24 h-24 rounded-full bg-green-100 flex items-center justify-center mb-4"
                >
                  <CheckCircle className="w-14 h-14 text-green-500" />
                </motion.div>
                <h2 className="text-2xl font-bold text-gray-900">Session terminée</h2>
                <p className="text-gray-500 text-sm mt-1">Merci d'avoir utilisé SmartAccès</p>
              </div>

              {/* Receipt */}
              <StaggerContainer className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                <div className="px-4 pt-4 pb-2">
                  <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Reçu</p>
                  <StaggerItem>
                    <div className="flex justify-between py-2">
                      <span className="text-sm text-gray-500">Service</span>
                      <span className="text-sm font-medium text-gray-800">{activeReservation?.serviceName}</span>
                    </div>
                  </StaggerItem>
                  <StaggerItem>
                    <div className="flex justify-between py-2">
                      <span className="text-sm text-gray-500">Durée</span>
                      <span className="text-sm font-medium text-gray-800">{formatDuration(elapsed)}</span>
                    </div>
                  </StaggerItem>
                  <StaggerItem>
                    <div className="flex justify-between py-2">
                      <span className="text-sm text-gray-500">Caution versée</span>
                      <span className="text-sm font-medium text-gray-800">{formatPrice(deposit)}</span>
                    </div>
                  </StaggerItem>
                  <StaggerItem>
                    <div className="flex justify-between py-2">
                      <span className="text-sm text-gray-500">Coût réel</span>
                      <span className="text-sm font-medium text-gray-800">{formatPrice(currentCostCents)}</span>
                    </div>
                  </StaggerItem>
                </div>

                {/* Divider */}
                <div className="mx-4 border-t border-dashed border-gray-200 my-1" />

                {/* Refund */}
                <StaggerItem>
                  <div className="flex justify-between items-center px-4 py-4">
                    <div className="flex items-center gap-2">
                      <ArrowDownLeft className="w-5 h-5 text-green-500" />
                      <span className="text-base font-semibold text-gray-700">Remboursement</span>
                    </div>
                    <span className="text-xl font-bold text-green-600">{formatPrice(refund)}</span>
                  </div>
                </StaggerItem>
              </StaggerContainer>

              {/* Info text */}
              <motion.p
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: 0.5 }}
                className="text-center text-xs text-gray-400 px-4"
              >
                Le remboursement sera effectué sous 24 à 48h sur votre moyen de paiement.
              </motion.p>

              {/* Buttons */}
              <motion.div
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.4 }}
                className="space-y-3 pb-4"
              >
                <motion.button
                  whileTap={{ scale: 0.97 }}
                  onClick={() => router.push('/reserver')}
                  className="w-full bg-indigo-600 text-white py-4 rounded-xl font-semibold flex items-center justify-center gap-2"
                >
                  <PlusCircle className="w-4 h-4" />
                  Nouvelle réservation
                </motion.button>
                <motion.button
                  whileTap={{ scale: 0.97 }}
                  onClick={() => router.push('/')}
                  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"
                >
                  <Home className="w-4 h-4" />
                  Retour à l'accueil
                </motion.button>
              </motion.div>
            </motion.div>
          )}

        </AnimatePresence>
      </div>
    </PageTransition>
  )
}
