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

interface Program {
  rank: number
  name: string
  revenue: string
  percentage: number
}

export default function ProgramTable() {
  const [programs, setPrograms] = useState<Program[]>([])

  useEffect(() => {
    api.getProgramRanking().then(res => setPrograms(res.data)).catch(console.error)
  }, [])

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5, delay: 0.4 }}
      className="bg-card rounded-xl border border-border p-5 lg:p-6"
    >
      <div className="flex items-center justify-between mb-5">
        <h2 className="text-base lg:text-lg font-semibold text-ink m-0">
          Top filieres par CA
        </h2>
        <a href="/rapports" className="text-xs text-accent font-medium hover:text-accent-hover transition-colors">
          Voir le rapport complet &rarr;
        </a>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-border">
              <th className="text-left py-3 px-2 text-xs font-medium text-muted uppercase tracking-wider">#</th>
              <th className="text-left py-3 px-2 text-xs font-medium text-muted uppercase tracking-wider">Filiere</th>
              <th className="text-right py-3 px-2 text-xs font-medium text-muted uppercase tracking-wider">CA (MAD)</th>
              <th className="text-right py-3 px-2 text-xs font-medium text-muted uppercase tracking-wider">Part</th>
            </tr>
          </thead>
          <tbody>
            {programs.map((program) => (
              <tr key={program.rank} className="border-b border-border/50 last:border-0 hover:bg-bg/50 transition-colors">
                <td className="py-3.5 px-2 text-muted font-medium">{program.rank}</td>
                <td className="py-3.5 px-2 font-medium text-ink">{program.name}</td>
                <td className="py-3.5 px-2 text-right text-ink">{program.revenue} MAD</td>
                <td className="py-3.5 px-2 text-right">
                  <div className="flex items-center justify-end gap-2">
                    <div className="w-16 h-1.5 bg-border rounded-full overflow-hidden hidden sm:block">
                      <motion.div
                        initial={{ width: 0 }}
                        animate={{ width: `${program.percentage}%` }}
                        transition={{ duration: 0.8, delay: 0.5 + program.rank * 0.1 }}
                        className="h-full bg-accent rounded-full"
                      />
                    </div>
                    <span className="font-medium text-ink">{program.percentage}%</span>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </motion.div>
  )
}
