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

function formatMAD(value: number) {
  return value.toLocaleString('fr-FR') + ' MAD'
}

interface PaiementForm {
  etudiantId: string
  montant: number | ''
  modePaiement: string
}

const emptyForm: PaiementForm = {
  etudiantId: '',
  montant: '',
  modePaiement: '',
}

export default function Paiements() {
  const [paiements, setPaiements] = useState<any[]>([])
  const [kpis, setKpis] = useState({ totalMois: 0, enRetard: 0, montantImpayes: 0 })
  const [loading, setLoading] = useState(true)

  // Modal state
  const [modalOpen, setModalOpen] = useState(false)
  const [form, setForm] = useState<PaiementForm>(emptyForm)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState<{ show: boolean; paiementId?: number }>({ show: false })

  // Student search
  const [studentSearch, setStudentSearch] = useState('')
  const [studentResults, setStudentResults] = useState<any[]>([])
  const [selectedStudent, setSelectedStudent] = useState<any>(null)
  const [showDropdown, setShowDropdown] = useState(false)
  const searchTimeout = useRef<ReturnType<typeof setTimeout> | null>(null)
  const dropdownRef = useRef<HTMLDivElement>(null)

  const fetchData = () => {
    setLoading(true)
    api.getPaiements()
      .then(res => {
        setPaiements(res.data)
        setKpis(res.kpis)
      })
      .catch(console.error)
      .finally(() => setLoading(false))
  }

  useEffect(() => {
    fetchData()
  }, [])

  // Close dropdown on outside click
  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setShowDropdown(false)
      }
    }
    document.addEventListener('mousedown', handleClick)
    return () => document.removeEventListener('mousedown', handleClick)
  }, [])

  const searchStudents = (query: string) => {
    setStudentSearch(query)
    setSelectedStudent(null)
    setForm(f => ({ ...f, etudiantId: '' }))

    if (searchTimeout.current) clearTimeout(searchTimeout.current)

    if (query.length < 2) {
      setStudentResults([])
      setShowDropdown(false)
      return
    }

    searchTimeout.current = setTimeout(() => {
      api.getEtudiants({ search: query, limit: 10 })
        .then(res => {
          setStudentResults(res.data)
          setShowDropdown(true)
        })
        .catch(console.error)
    }, 300)
  }

  const selectStudent = (student: any) => {
    setSelectedStudent(student)
    setStudentSearch(student.nom)
    setForm(f => ({ ...f, etudiantId: student.id.toString() }))
    setShowDropdown(false)
  }

  const openModal = () => {
    setForm(emptyForm)
    setStudentSearch('')
    setSelectedStudent(null)
    setError('')
    setSuccess({ show: false })
    setModalOpen(true)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!form.etudiantId) {
      setError('Veuillez selectionner un etudiant')
      return
    }
    setError('')
    setSubmitting(true)

    try {
      const result = await api.createPaiement({
        etudiantId: Number(form.etudiantId),
        montant: Number(form.montant),
        modePaiement: form.modePaiement,
      })
      setSuccess({ show: true, paiementId: result.id })
      fetchData()
    } catch (err: any) {
      setError(err.message || 'Erreur lors de l\'enregistrement')
    } finally {
      setSubmitting(false)
    }
  }

  const downloadReceipt = (paiementId: number) => {
    const token = localStorage.getItem('ispm_token')
    const url = `${import.meta.env.VITE_API_URL || 'http://localhost:3001/api'}/paiements/${paiementId}/recu`
    const a = document.createElement('a')
    a.href = `${url}?token=${token}`
    a.target = '_blank'
    a.click()
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <h1 className="text-xl lg:text-2xl font-bold text-ink">Paiements</h1>
        <button
          onClick={openModal}
          className="px-4 py-2.5 bg-accent text-white text-sm font-medium rounded-lg hover:bg-accent/90 transition-colors"
        >
          Enregistrer un paiement
        </button>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3, delay: 0 }}
          className="bg-card rounded-xl border border-border p-4"
        >
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-green-50 flex items-center justify-center">
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="#10B981" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M10 2v16M6 6l4-4 4 4M6 14l4 4 4-4" />
              </svg>
            </div>
            <div>
              <div className="text-xs text-muted">Total encaisse ce mois</div>
              <div className="text-lg font-bold text-ink">{formatMAD(kpis.totalMois)}</div>
            </div>
          </div>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3, delay: 0.08 }}
          className="bg-card rounded-xl border border-border p-4"
        >
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-orange-50 flex items-center justify-center">
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="#F59E0B" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="10" cy="10" r="7" />
                <path d="M10 6v4l2.5 2.5" />
              </svg>
            </div>
            <div>
              <div className="text-xs text-muted">Paiements en retard</div>
              <div className="text-lg font-bold text-ink">{kpis.enRetard}</div>
            </div>
          </div>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3, delay: 0.16 }}
          className="bg-card rounded-xl border border-border p-4"
        >
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-red-50 flex items-center justify-center">
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="#EF4444" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M10 2l8 14H2L10 2z" />
                <path d="M10 8v3M10 14h.01" />
              </svg>
            </div>
            <div>
              <div className="text-xs text-muted">Montant impayes</div>
              <div className="text-lg font-bold text-ink">{formatMAD(kpis.montantImpayes)}</div>
            </div>
          </div>
        </motion.div>
      </div>

      {/* Alert banner */}
      {kpis.enRetard > 0 && (
        <div className="flex items-center gap-3 px-4 py-3 bg-amber-50 border border-amber-200 rounded-lg mb-6">
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="#D97706" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M9 2l7 12H2L9 2z" />
            <path d="M9 7v3M9 13h.01" />
          </svg>
          <span className="text-sm text-amber-800">{kpis.enRetard} etudiants ont des paiements en retard. Veuillez les contacter.</span>
        </div>
      )}

      {/* Payments table */}
      <div className="bg-card rounded-xl border border-border overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-bg">
                <th className="text-left px-5 py-3.5 font-medium text-muted">Date</th>
                <th className="text-left px-5 py-3.5 font-medium text-muted">Etudiant</th>
                <th className="text-right px-5 py-3.5 font-medium text-muted">Montant</th>
                <th className="text-left px-5 py-3.5 font-medium text-muted">Mode</th>
                <th className="text-left px-5 py-3.5 font-medium text-muted">Statut</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={5} className="px-5 py-8 text-center text-muted">Chargement...</td></tr>
              ) : paiements.length === 0 ? (
                <tr><td colSpan={5} className="px-5 py-8 text-center text-muted">Aucun paiement</td></tr>
              ) : (
                paiements.map((p) => (
                  <tr key={p.id} className="border-b border-border last:border-0 hover:bg-bg/50 transition-colors">
                    <td className="px-5 py-3.5 text-ink">{p.date}</td>
                    <td className="px-5 py-3.5 font-medium text-ink">{p.etudiant}</td>
                    <td className="px-5 py-3.5 text-right font-medium text-ink">{formatMAD(p.montant)}</td>
                    <td className="px-5 py-3.5 text-muted">{p.mode}</td>
                    <td className="px-5 py-3.5">
                      <span className="inline-block px-2.5 py-1 rounded-full text-xs font-medium bg-green-100 text-green-700">
                        {p.statut}
                      </span>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Payment Modal */}
      <Modal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        title="Enregistrer un paiement"
      >
        {success.show ? (
          <div className="text-center py-4">
            <div className="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#10B981" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20 6L9 17l-5-5" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-ink mb-2">Paiement enregistre</h3>
            <p className="text-sm text-muted mb-4">Le paiement a ete enregistre avec succes.</p>
            <div className="flex items-center justify-center gap-3">
              {success.paiementId && (
                <button
                  onClick={() => downloadReceipt(success.paiementId!)}
                  className="px-4 py-2.5 text-sm font-medium text-accent border border-accent/30 rounded-lg hover:bg-accent/5 transition-colors"
                >
                  Telecharger le recu PDF
                </button>
              )}
              <button
                onClick={() => setModalOpen(false)}
                className="px-4 py-2.5 text-sm font-medium text-white bg-accent rounded-lg hover:bg-accent/90 transition-colors"
              >
                Fermer
              </button>
            </div>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="space-y-4">
            {error && (
              <div className="px-3 py-2 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
                {error}
              </div>
            )}

            {/* Searchable student dropdown */}
            <div ref={dropdownRef} className="relative">
              <label className="block text-sm font-medium text-ink mb-1.5">Etudiant</label>
              <input
                type="text"
                value={studentSearch}
                onChange={(e) => searchStudents(e.target.value)}
                onFocus={() => { if (studentResults.length > 0) setShowDropdown(true) }}
                className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-white focus:outline-none focus:ring-2 focus:ring-accent/20 focus:border-accent"
                placeholder="Rechercher un etudiant par nom..."
              />

              {showDropdown && studentResults.length > 0 && (
                <div className="absolute z-10 w-full mt-1 bg-white border border-border rounded-lg shadow-lg max-h-48 overflow-y-auto">
                  {studentResults.map(s => (
                    <button
                      key={s.id}
                      type="button"
                      onClick={() => selectStudent(s)}
                      className="w-full text-left px-3 py-2.5 text-sm hover:bg-bg transition-colors border-b border-border last:border-0"
                    >
                      <span className="font-medium text-ink">{s.nom}</span>
                      <span className="text-muted ml-2">- {s.filiere}</span>
                    </button>
                  ))}
                </div>
              )}

              {selectedStudent && (
                <div className="mt-1.5 text-xs text-muted">
                  Selectionne : {selectedStudent.nom} ({selectedStudent.filiere})
                </div>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-ink mb-1.5">Montant (MAD)</label>
              <input
                type="number"
                required
                min="1"
                value={form.montant}
                onChange={(e) => setForm(f => ({ ...f, montant: e.target.value ? Number(e.target.value) : '' }))}
                className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-white focus:outline-none focus:ring-2 focus:ring-accent/20 focus:border-accent"
                placeholder="Ex: 5000"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-ink mb-1.5">Mode de paiement</label>
              <select
                required
                value={form.modePaiement}
                onChange={(e) => setForm(f => ({ ...f, modePaiement: e.target.value }))}
                className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-white focus:outline-none focus:ring-2 focus:ring-accent/20 focus:border-accent"
              >
                <option value="">Selectionner un mode</option>
                <option value="Especes">Especes</option>
                <option value="Virement">Virement</option>
                <option value="Cheque">Cheque</option>
              </select>
            </div>

            <div className="flex items-center justify-end gap-3 pt-2">
              <button
                type="button"
                onClick={() => setModalOpen(false)}
                className="px-4 py-2.5 text-sm font-medium text-ink border border-border rounded-lg hover:bg-bg transition-colors"
              >
                Annuler
              </button>
              <button
                type="submit"
                disabled={submitting || !form.etudiantId}
                className="px-4 py-2.5 text-sm font-medium text-white bg-accent rounded-lg hover:bg-accent/90 transition-colors disabled:opacity-50"
              >
                {submitting ? 'Enregistrement...' : 'Enregistrer'}
              </button>
            </div>
          </form>
        )}
      </Modal>
    </motion.div>
  )
}
