'use client'

import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import {
  Clock,
  ChevronRight,
  CalendarDays,
  ArrowDownLeft,
  ReceiptText,
  PlusCircle,
} from 'lucide-react'
import { useRouter } from 'next/navigation'
import PageTransition, { StaggerContainer, StaggerItem } from '@/components/PageTransition'
import { pastReservations, type Reservation } from '@/lib/mock-data'
import { formatPrice, formatDuration } from '@/lib/utils'

function StatusBadge({ status }: { status: Reservation['status'] }) {
  if (status === 'completed') {
    return (
      <span className="text-xs font-semibold bg-green-100 text-green-700 px-2 py-0.5 rounded-full">
        Terminée
      </span>
    )
  }
  return (
    <span className="text-xs font-semibold bg-red-100 text-red-600 px-2 py-0.5 rounded-full">
      Annulée
    </span>
  )
}

export default function HistoriquePage() {
  const [expanded, setExpanded] = useState<string | null>(null)
  const router = useRouter()

  const totalRefunds = pastReservations.reduce((acc, r) => acc + (r.refund ?? 0), 0)

  const toggle = (id: string) => {
    setExpanded((prev) => (prev === id ? null : id))
  }

  if (pastReservations.length === 0) {
    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">
            <Clock className="w-12 h-12 text-gray-300" />
          </div>
          <div>
            <h2 className="text-xl font-bold text-gray-800 mb-2">Aucune réservation</h2>
            <p className="text-gray-500 text-sm">Votre historique apparaîtra ici</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 flex items-center gap-2"
          >
            <PlusCircle className="w-4 h-4" />
            Réserver un espace
          </motion.button>
        </div>
      </PageTransition>
    )
  }

  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">
            <Clock className="w-5 h-5 text-indigo-600" />
          </div>
          <h1 className="text-2xl font-bold text-gray-900">Historique</h1>
        </div>

        {/* Stats bar */}
        <div className="flex gap-3 overflow-x-auto pb-1 -mx-1 px-1 scrollbar-hide">
          <div className="flex-shrink-0 bg-white rounded-2xl px-4 py-3 shadow-sm border border-gray-100 flex items-center gap-3 min-w-[160px]">
            <div className="w-9 h-9 rounded-xl bg-indigo-100 flex items-center justify-center">
              <ReceiptText className="w-4 h-4 text-indigo-600" />
            </div>
            <div>
              <p className="text-xs text-gray-500">Total réservations</p>
              <p className="text-lg font-bold text-gray-900">{pastReservations.length}</p>
            </div>
          </div>
          <div className="flex-shrink-0 bg-white rounded-2xl px-4 py-3 shadow-sm border border-gray-100 flex items-center gap-3 min-w-[160px]">
            <div className="w-9 h-9 rounded-xl bg-green-100 flex items-center justify-center">
              <ArrowDownLeft className="w-4 h-4 text-green-600" />
            </div>
            <div>
              <p className="text-xs text-gray-500">Total remboursé</p>
              <p className="text-lg font-bold text-green-700">{formatPrice(totalRefunds)}</p>
            </div>
          </div>
        </div>

        {/* List */}
        <StaggerContainer className="space-y-3">
          {pastReservations.map((res) => {
            const isExpanded = expanded === res.id
            const isCompleted = res.status === 'completed'

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

            return (
              <StaggerItem key={res.id}>
                <motion.div
                  layout
                  onClick={() => toggle(res.id)}
                  className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden cursor-pointer"
                  whileTap={{ scale: 0.99 }}
                >
                  {/* Main row */}
                  <div className="p-4">
                    <div className="flex items-start justify-between gap-3">
                      <div className="flex items-start gap-3">
                        {/* Status dot */}
                        <div className="mt-1.5 flex-shrink-0">
                          <div
                            className={`w-2.5 h-2.5 rounded-full ${
                              isCompleted ? 'bg-green-500' : 'bg-red-400'
                            }`}
                          />
                        </div>
                        <div>
                          <p className="font-bold text-gray-900 text-sm">{res.serviceName}</p>
                          <p className="text-xs text-gray-500 capitalize mt-0.5">{dateFormatted}</p>
                          <p className="text-xs text-gray-400 mt-0.5">{res.timeSlot}</p>
                        </div>
                      </div>
                      <div className="flex items-start gap-2">
                        <StatusBadge status={res.status} />
                        <motion.div
                          animate={{ rotate: isExpanded ? 90 : 0 }}
                          transition={{ duration: 0.2 }}
                        >
                          <ChevronRight className="w-4 h-4 text-gray-400 mt-0.5" />
                        </motion.div>
                      </div>
                    </div>

                    {/* Bottom row */}
                    <div className="flex items-center gap-3 mt-3 pt-3 border-t border-gray-50">
                      <span className="text-xs text-gray-500">
                        Caution : <span className="font-medium text-gray-700">{formatPrice(res.deposit)}</span>
                      </span>
                      <span className="text-gray-200">·</span>
                      <span className="text-xs text-gray-500">
                        Coût : <span className="font-medium text-gray-700">{formatPrice(res.actualCost ?? 0)}</span>
                      </span>
                      {res.refund !== null && res.refund > 0 && (
                        <>
                          <span className="text-gray-200">·</span>
                          <span className="text-xs font-semibold text-green-600">
                            +{formatPrice(res.refund)} remboursé
                          </span>
                        </>
                      )}
                    </div>
                  </div>

                  {/* Expanded details */}
                  <AnimatePresence>
                    {isExpanded && (
                      <motion.div
                        initial={{ height: 0, opacity: 0 }}
                        animate={{ height: 'auto', opacity: 1 }}
                        exit={{ height: 0, opacity: 0 }}
                        transition={{ duration: 0.25, ease: [0.25, 0.1, 0.25, 1] }}
                        className="overflow-hidden"
                      >
                        <div className="border-t border-gray-100 mx-4 mb-1" />
                        <div className="px-4 pb-4 space-y-2">
                          <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mt-2 mb-2">
                            Détails
                          </p>
                          {[
                            { label: 'Code PIN', value: res.pin },
                            {
                              label: 'Durée',
                              value: res.duration ? formatDuration(res.duration * 60) : 'Annulée',
                            },
                            { label: 'Caution versée', value: formatPrice(res.deposit) },
                            {
                              label: 'Coût final',
                              value: res.actualCost !== null ? formatPrice(res.actualCost) : '—',
                            },
                            {
                              label: 'Remboursement',
                              value: res.refund !== null ? formatPrice(res.refund) : '—',
                              cls: 'text-green-600 font-semibold',
                            },
                          ].map(({ label, value, cls }) => (
                            <div key={label} className="flex justify-between items-center">
                              <span className="text-xs text-gray-500">{label}</span>
                              <span className={`text-xs font-medium text-gray-800 ${cls ?? ''}`}>
                                {value}
                              </span>
                            </div>
                          ))}
                        </div>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </motion.div>
              </StaggerItem>
            )
          })}
        </StaggerContainer>

      </div>
    </PageTransition>
  )
}
