import { motion } from 'framer-motion'
import { Link } from 'react-router-dom'
import { useState, useEffect } from 'react'
import { api } from '@/lib/api'
import { useAuth } from '@/lib/auth'
import Modal from '@/components/Modal'
import ConfirmDialog from '@/components/ConfirmDialog'

const statutColors: Record<string, string> = {
  ACTIF: 'bg-green-100 text-green-700',
  SUSPENDU: 'bg-orange-100 text-orange-700',
  ABANDON: 'bg-red-100 text-red-700',
  DIPLOME: 'bg-blue-100 text-blue-700',
}

const statutLabels: Record<string, string> = {
  ACTIF: 'Actif',
  SUSPENDU: 'Suspendu',
  ABANDON: 'Abandon',
  DIPLOME: 'Diplome',
}

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

interface EtudiantForm {
  nom: string
  prenom: string
  cin: string
  dateNaissance: string
  telephone: string
  email: string
  adresse: string
  filiereId: string
  niveau: string
}

const emptyForm: EtudiantForm = {
  nom: '',
  prenom: '',
  cin: '',
  dateNaissance: '',
  telephone: '',
  email: '',
  adresse: '',
  filiereId: '',
  niveau: '',
}

export default function Etudiants() {
  const { user } = useAuth()
  const [students, setStudents] = useState<any[]>([])
  const [pagination, setPagination] = useState({ page: 1, total: 0, totalPages: 1 })
  const [search, setSearch] = useState('')
  const [filiereFilter, setFiliereFilter] = useState('')
  const [statutFilter, setStatutFilter] = useState('')
  const [filieres, setFilieres] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  // Modal state
  const [modalOpen, setModalOpen] = useState(false)
  const [editingId, setEditingId] = useState<number | null>(null)
  const [form, setForm] = useState<EtudiantForm>(emptyForm)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')

  // Delete state
  const [deleteId, setDeleteId] = useState<number | null>(null)
  const [deleting, setDeleting] = useState(false)
  const [pendingStatusChange, setPendingStatusChange] = useState<{ id: number; statut: string } | null>(null)

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

  const fetchStudents = () => {
    setLoading(true)
    api.getEtudiants({
      page: pagination.page,
      limit: 10,
      search: search || undefined,
      filiereId: filiereFilter ? parseInt(filiereFilter) : undefined,
      statut: statutFilter || undefined,
    }).then(res => {
      setStudents(res.data)
      setPagination(prev => ({ ...prev, total: res.pagination.total, totalPages: res.pagination.totalPages }))
    }).catch(console.error).finally(() => setLoading(false))
  }

  useEffect(() => {
    fetchStudents()
  }, [pagination.page, search, filiereFilter, statutFilter])

  const handleSearch = (value: string) => {
    setSearch(value)
    setPagination(prev => ({ ...prev, page: 1 }))
  }

  const openAdd = () => {
    setForm(emptyForm)
    setEditingId(null)
    setError('')
    setModalOpen(true)
  }

  const openEdit = (student: any) => {
    setForm({
      nom: student.nomFamille || student.nom || '',
      prenom: student.prenom || '',
      cin: student.cin || '',
      dateNaissance: student.dateNaissance || '',
      telephone: student.telephone || '',
      email: student.email || '',
      adresse: student.adresse || '',
      filiereId: student.filiereId?.toString() || '',
      niveau: student.niveau || '',
    })
    setEditingId(student.id)
    setError('')
    setModalOpen(true)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    setSubmitting(true)

    const payload = {
      nom: form.nom,
      prenom: form.prenom,
      cin: form.cin,
      dateNaissance: form.dateNaissance,
      telephone: form.telephone,
      email: form.email,
      adresse: form.adresse,
      filiereId: Number(form.filiereId),
      niveau: form.niveau,
    }

    try {
      if (editingId) {
        await api.updateEtudiant(editingId, payload)
      } else {
        await api.createEtudiant(payload)
      }
      setModalOpen(false)
      fetchStudents()
    } catch (err: any) {
      setError(err.message || 'Erreur lors de la sauvegarde')
    } finally {
      setSubmitting(false)
    }
  }

  const handleDelete = async () => {
    if (!deleteId) return
    setDeleting(true)
    try {
      await api.deleteEtudiant(deleteId)
      setDeleteId(null)
      fetchStudents()
    } catch (err: any) {
      setError(err.message || 'Erreur lors de la suppression')
      setDeleteId(null)
    } finally {
      setDeleting(false)
    }
  }

  const handleStatusUpdate = async () => {
    if (!pendingStatusChange) return

    const response = await fetch(`/api/etudiants/${pendingStatusChange.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ statut: pendingStatusChange.statut }),
    })

    if (!response.ok) {
      throw new Error("Impossible de mettre a jour le statut")
    }

    setStudents((currentStudents: any[]) =>
      currentStudents.map((student: any) =>
        student.id === pendingStatusChange.id
          ? { ...student, statut: pendingStatusChange.statut }
          : student,
      ),
    )
    setPendingStatusChange(null)
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      {/* Header */}
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
        <h1 className="text-xl lg:text-2xl font-bold text-ink">Etudiants</h1>
        <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
          {/* Search */}
          <div className="relative">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" className="absolute left-3 top-1/2 -translate-y-1/2 text-muted">
              <circle cx="7" cy="7" r="4.5" />
              <path d="M10.5 10.5L14 14" strokeLinecap="round" />
            </svg>
            <input
              type="text"
              placeholder="Rechercher un etudiant..."
              value={search}
              onChange={(e) => handleSearch(e.target.value)}
              className="pl-9 pr-4 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-accent/20 focus:border-accent w-full sm:w-56"
            />
          </div>
          {/* Filters */}
          <select
            value={filiereFilter}
            onChange={(e) => { setFiliereFilter(e.target.value); setPagination(p => ({ ...p, page: 1 })) }}
            className="px-3 py-2.5 border border-border rounded-lg text-sm bg-card text-ink focus:outline-none focus:ring-2 focus:ring-accent/20"
          >
            <option value="">Toutes les filieres</option>
            {filieres.map(f => (
              <option key={f.id} value={f.id}>{f.name}</option>
            ))}
          </select>
          <select
            value={statutFilter}
            onChange={(e) => { setStatutFilter(e.target.value); setPagination(p => ({ ...p, page: 1 })) }}
            className="px-3 py-2.5 border border-border rounded-lg text-sm bg-card text-ink focus:outline-none focus:ring-2 focus:ring-accent/20"
          >
            <option value="">Tous les statuts</option>
            <option value="ACTIF">Actif</option>
            <option value="SUSPENDU">Suspendu</option>
            <option value="ABANDON">Abandon</option>
            <option value="DIPLOME">Diplome</option>
          </select>
          <button
            onClick={openAdd}
            className="px-4 py-2.5 bg-accent text-white text-sm font-medium rounded-lg hover:bg-accent/90 transition-colors whitespace-nowrap"
          >
            Ajouter un etudiant
          </button>
        </div>
      </div>

      {/* 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">Nom complet</th>
                <th className="text-left px-5 py-3.5 font-medium text-muted">Filiere</th>
                <th className="text-left px-5 py-3.5 font-medium text-muted">Statut</th>
                <th className="text-left px-5 py-3.5 font-medium text-muted">Telephone</th>
                <th className="text-right px-5 py-3.5 font-medium text-muted">Solde restant</th>
                <th className="text-right px-5 py-3.5 font-medium text-muted">Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={6} className="px-5 py-8 text-center text-muted">Chargement...</td></tr>
              ) : students.length === 0 ? (
                <tr><td colSpan={6} className="px-5 py-8 text-center text-muted">Aucun etudiant trouve</td></tr>
              ) : (
                students.map((student) => (
                  <tr key={student.id} className="border-b border-border last:border-0 hover:bg-bg/50 transition-colors">
                    <td className="px-5 py-3.5">
                      <Link to={`/etudiants/${student.id}`} className="font-medium text-ink hover:text-accent transition-colors">
                        {student.nom}
                      </Link>
                    </td>
                    <td className="px-5 py-3.5 text-muted">{student.filiere}</td>
                    <td className="px-5 py-3.5">
                      <span className={`inline-block px-2.5 py-1 rounded-full text-xs font-medium ${statutColors[student.statut] || ''}`}>
                        {statutLabels[student.statut] || student.statut}
                      </span>
                    </td>
                    <td className="px-5 py-3.5 text-muted">{student.telephone}</td>
                    <td className="px-5 py-3.5 text-right font-medium text-ink">{formatMAD(student.solde)}</td>
                    <td className="px-5 py-3.5 text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Link
                          to={`/etudiants/${student.id}`}
                          className="px-2.5 py-1 text-xs font-medium text-accent border border-accent/30 rounded-lg hover:bg-accent/5 transition-colors"
                        >
                          Voir
                        </Link>
                        <button
                          onClick={() => openEdit(student)}
                          className="px-2.5 py-1 text-xs font-medium text-ink border border-border rounded-lg hover:bg-bg transition-colors"
                        >
                          Modifier
                        </button>
                        {user?.role === 'ADMIN' && <button
                          onClick={() => setDeleteId(student.id)}
                          className="px-2.5 py-1 text-xs font-medium text-red-600 border border-red-200 rounded-lg hover:bg-red-50 transition-colors"
                        >
                          Supprimer
                        </button>}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        <div className="flex items-center justify-between px-5 py-3.5 border-t border-border">
          <span className="text-sm text-muted">
            Page {pagination.page} sur {pagination.totalPages} ({pagination.total} etudiants)
          </span>
          <div className="flex items-center gap-1">
            <button
              onClick={() => setPagination(p => ({ ...p, page: Math.max(1, p.page - 1) }))}
              disabled={pagination.page === 1}
              className="px-3 py-1.5 text-sm rounded-lg border border-border text-muted hover:bg-bg transition-colors disabled:opacity-50"
            >
              Precedent
            </button>
            {Array.from({ length: Math.min(5, pagination.totalPages) }, (_, i) => i + 1).map(page => (
              <button
                key={page}
                onClick={() => setPagination(p => ({ ...p, page }))}
                className={`px-3 py-1.5 text-sm rounded-lg ${
                  page === pagination.page
                    ? 'bg-accent text-white font-medium'
                    : 'border border-border text-muted hover:bg-bg transition-colors'
                }`}
              >
                {page}
              </button>
            ))}
            <button
              onClick={() => setPagination(p => ({ ...p, page: Math.min(p.totalPages, p.page + 1) }))}
              disabled={pagination.page === pagination.totalPages}
              className="px-3 py-1.5 text-sm rounded-lg border border-border text-muted hover:bg-bg transition-colors disabled:opacity-50"
            >
              Suivant
            </button>
          </div>
        </div>
      </div>

      {/* Add/Edit Modal */}
      <Modal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        title={editingId ? 'Modifier l\'etudiant' : 'Ajouter un etudiant'}
      >
        <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>
          )}

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-ink mb-1.5">Nom</label>
              <input
                type="text"
                required
                value={form.nom}
                onChange={(e) => setForm(f => ({ ...f, nom: 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="Nom de famille"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-ink mb-1.5">Prenom</label>
              <input
                type="text"
                required
                value={form.prenom}
                onChange={(e) => setForm(f => ({ ...f, prenom: 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="Prenom"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-ink mb-1.5">CIN</label>
              <input
                type="text"
                required
                value={form.cin}
                onChange={(e) => setForm(f => ({ ...f, cin: 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: AB123456"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-ink mb-1.5">Date de naissance</label>
              <input
                type="date"
                required
                value={form.dateNaissance}
                onChange={(e) => setForm(f => ({ ...f, dateNaissance: 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"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-ink mb-1.5">Telephone</label>
              <input
                type="tel"
                required
                value={form.telephone}
                onChange={(e) => setForm(f => ({ ...f, telephone: 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: 0612345678"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-ink mb-1.5">Email</label>
              <input
                type="email"
                required
                value={form.email}
                onChange={(e) => setForm(f => ({ ...f, email: 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="email@exemple.com"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-ink mb-1.5">Adresse</label>
            <input
              type="text"
              value={form.adresse}
              onChange={(e) => setForm(f => ({ ...f, adresse: 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="Adresse complete"
            />
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-ink mb-1.5">Filiere</label>
              <select
                required
                value={form.filiereId}
                onChange={(e) => setForm(f => ({ ...f, filiereId: 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 une filiere</option>
                {filieres.map(f => (
                  <option key={f.id} value={f.id}>{f.name}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-ink mb-1.5">Niveau</label>
              <select
                required
                value={form.niveau}
                onChange={(e) => setForm(f => ({ ...f, niveau: 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 niveau</option>
                <option value="1ere annee">1ere annee</option>
                <option value="2eme annee">2eme annee</option>
              </select>
            </div>
          </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}
              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...' : (editingId ? 'Mettre a jour' : 'Ajouter')}
            </button>
          </div>
        </form>
      </Modal>

      {/* Delete Confirmation */}
      <ConfirmDialog
        open={deleteId !== null}
        onClose={() => setDeleteId(null)}
        onConfirm={handleDelete}
        title="Supprimer l'etudiant"
        message="Etes-vous sur de vouloir supprimer cet etudiant ? Cette action est irreversible."
        loading={deleting}
      />

      <ConfirmDialog
        open={pendingStatusChange !== null}
        onClose={() => setPendingStatusChange(null)}
        onConfirm={() => void handleStatusUpdate()}
        title="Changer le statut"
        message="Voulez-vous confirmer ce changement de statut pour cet etudiant ?"
        confirmLabel="Confirmer"
      />
    </motion.div>
  )
}
