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

const rapports = [
  {
    title: 'Rapport des inscriptions',
    description: 'Liste detaillee de toutes les inscriptions par filiere et par annee scolaire.',
    icon: 'inscriptions',
    endpoint: 'inscriptions',
  },
  {
    title: 'Rapport financier mensuel',
    description: 'Synthese des recettes et depenses du mois en cours.',
    icon: 'mensuel',
    endpoint: 'financier-mensuel',
  },
  {
    title: 'Rapport financier annuel',
    description: "Bilan financier complet de l'annee academique.",
    icon: 'annuel',
    endpoint: 'financier-annuel',
  },
  {
    title: 'Rapport des impayes',
    description: 'Liste des etudiants avec des paiements en retard ou non regles.',
    icon: 'impayes',
    endpoint: 'impayes',
  },
  {
    title: 'Rapport CA par filiere',
    description: "Chiffre d'affaires previsionnel et realise par programme.",
    icon: 'ca',
    endpoint: 'ca-par-filiere',
  },
  {
    title: 'Rapport de recouvrement',
    description: 'Suivi des actions de recouvrement et taux de recuperation.',
    icon: 'recouvrement',
    endpoint: 'recouvrement',
  },
]

function ReportIcon({ type }: { type: string }) {
  switch (type) {
    case 'inscriptions':
      return (
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="8" r="4" />
          <path d="M5 20c0-4 3.13-7 7-7s7 3 7 7" />
        </svg>
      )
    case 'mensuel':
      return (
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="4" width="18" height="16" rx="2" />
          <path d="M3 9h18M8 2v4M16 2v4" />
        </svg>
      )
    case 'annuel':
      return (
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M3 3v18h18" />
          <path d="M7 16l4-6 4 4 4-8" />
        </svg>
      )
    case 'impayes':
      return (
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 2l9 16H3L12 2z" />
          <path d="M12 9v4M12 16h.01" />
        </svg>
      )
    case 'ca':
      return (
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <rect x="2" y="12" width="4" height="8" rx="1" />
          <rect x="8" y="8" width="4" height="12" rx="1" />
          <rect x="14" y="4" width="4" height="16" rx="1" />
          <rect x="20" y="6" width="2" height="14" rx="1" />
        </svg>
      )
    case 'recouvrement':
      return (
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="9" />
          <path d="M12 7v5l3 3" />
        </svg>
      )
    default:
      return null
  }
}

export default function Rapports() {
  const [downloading, setDownloading] = useState<string | null>(null)

  const handleDownload = async (endpoint: string, format: 'pdf' | 'excel') => {
    setDownloading(`${endpoint}-${format}`)
    try {
      await api.downloadRapport(endpoint, format)
    } catch (error) {
      console.error('Download error:', error)
    } finally {
      setDownloading(null)
    }
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-xl lg:text-2xl font-bold text-ink">Rapports</h1>
      </div>

      {/* Reports Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-6">
        {rapports.map((rapport, index) => (
          <motion.div
            key={rapport.title}
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3, delay: index * 0.06 }}
            className="bg-card rounded-xl border border-border p-5 hover:shadow-md transition-shadow flex flex-col"
          >
            <div className="w-10 h-10 rounded-lg bg-accent/10 flex items-center justify-center text-accent mb-4">
              <ReportIcon type={rapport.icon} />
            </div>
            <h3 className="text-base font-semibold text-ink mb-2">{rapport.title}</h3>
            <p className="text-sm text-muted mb-5 flex-1">{rapport.description}</p>
            <div className="flex items-center gap-3">
              <button
                onClick={() => handleDownload(rapport.endpoint, 'pdf')}
                disabled={downloading === `${rapport.endpoint}-pdf`}
                className="flex items-center gap-2 px-3 py-2 bg-red-50 text-red-700 rounded-lg text-xs font-medium hover:bg-red-100 transition-colors disabled:opacity-50"
              >
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M7 2v8M4 7l3 3 3-3" />
                  <path d="M2 11h10" />
                </svg>
                {downloading === `${rapport.endpoint}-pdf` ? '...' : 'Telecharger PDF'}
              </button>
              <button
                onClick={() => handleDownload(rapport.endpoint, 'excel')}
                disabled={downloading === `${rapport.endpoint}-excel`}
                className="flex items-center gap-2 px-3 py-2 bg-green-50 text-green-700 rounded-lg text-xs font-medium hover:bg-green-100 transition-colors disabled:opacity-50"
              >
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M7 2v8M4 7l3 3 3-3" />
                  <path d="M2 11h10" />
                </svg>
                {downloading === `${rapport.endpoint}-excel` ? '...' : 'Exporter Excel'}
              </button>
            </div>
          </motion.div>
        ))}
      </div>
    </motion.div>
  )
}
