import { motion } from 'framer-motion'
import { useState, useEffect } from 'react'
import { api } from '@/lib/api'

interface KPIData {
  totalEtudiants: number
  caRealise: number
  tauxRecouvrement: number
  impayes: number
  changes: {
    etudiants: string
    ca: string
    recouvrement: string
    impayes: string
  }
}

function StudentsIcon() {
  return (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="text-accent">
      <circle cx="12" cy="7" r="4" />
      <path d="M4 21c0-4.42 3.58-8 8-8s8 3.58 8 8" />
    </svg>
  )
}

function RevenueIcon() {
  return (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="text-accent">
      <rect x="2" y="4" width="20" height="16" rx="2" />
      <path d="M12 9v6M9 12h6" />
    </svg>
  )
}

function RecoveryIcon() {
  return (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="text-accent">
      <circle cx="12" cy="12" r="9" />
      <path d="M12 7v5l3 3" />
    </svg>
  )
}

function UnpaidIcon() {
  return (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="text-danger">
      <path d="M12 2L2 7l10 5 10-5-10-5z" />
      <path d="M2 17l10 5 10-5M2 12l10 5 10-5" />
    </svg>
  )
}

function formatValue(value: number, type: string): string {
  if (type === 'currency') {
    if (value >= 1000000) return `${(value / 1000000).toFixed(2)} M MAD`
    if (value >= 1000) return `${Math.round(value / 1000)}K MAD`
    return `${value} MAD`
  }
  if (type === 'percentage') return `${value}%`
  return value.toString()
}

const container = {
  hidden: { opacity: 0 },
  show: {
    opacity: 1,
    transition: { staggerChildren: 0.1 },
  },
}

const item = {
  hidden: { opacity: 0, y: 20 },
  show: { opacity: 1, y: 0, transition: { duration: 0.4, ease: 'easeOut' } },
}

export default function KPICards() {
  const [data, setData] = useState<KPIData | null>(null)

  useEffect(() => {
    api.getDashboardKPIs().then(setData).catch(console.error)
  }, [])

  if (!data) {
    return (
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 lg:gap-6">
        {[1, 2, 3, 4].map(i => (
          <div key={i} className="bg-card rounded-xl p-5 border border-border animate-pulse h-32" />
        ))}
      </div>
    )
  }

  const kpis = [
    { label: 'Total etudiants', value: formatValue(data.totalEtudiants, 'number'), change: data.changes.etudiants, changeType: 'positive' as const, icon: StudentsIcon },
    { label: 'CA Realise', value: formatValue(data.caRealise, 'currency'), change: data.changes.ca, changeType: 'positive' as const, icon: RevenueIcon },
    { label: 'Taux de recouvrement', value: formatValue(data.tauxRecouvrement, 'percentage'), change: data.changes.recouvrement, changeType: 'positive' as const, icon: RecoveryIcon },
    { label: 'Impayes', value: formatValue(data.impayes, 'currency'), change: data.changes.impayes, changeType: 'negative' as const, icon: UnpaidIcon },
  ]

  return (
    <motion.div
      variants={container}
      initial="hidden"
      animate="show"
      className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 lg:gap-6"
    >
      {kpis.map((kpi) => (
        <motion.div
          key={kpi.label}
          variants={item}
          whileHover={{ y: -2, boxShadow: '0 8px 25px -5px rgba(0,0,0,0.08)' }}
          className="bg-card rounded-xl p-5 border border-border transition-shadow"
        >
          <div className="flex items-start justify-between mb-3">
            <div className="w-10 h-10 rounded-lg bg-accent-light flex items-center justify-center">
              <kpi.icon />
            </div>
          </div>
          <div className="text-sm text-muted mb-1">{kpi.label}</div>
          <div className="text-2xl font-bold text-ink mb-2">{kpi.value}</div>
          <div className="flex items-center gap-2 text-xs">
            <span className={kpi.changeType === 'positive' ? 'text-success font-medium' : 'text-danger font-medium'}>
              {kpi.changeType === 'positive' ? '\u2191' : '\u2191'} {kpi.change}
            </span>
            <span className="text-muted">vs. annee precedente</span>
          </div>
        </motion.div>
      ))}
    </motion.div>
  )
}
