import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';
import { generateReceipt } from '../utils/pdf';
import path from 'path';

const prisma = new PrismaClient();

export async function getAll(req: Request, res: Response): Promise<void> {
  try {
    const page = parseInt(req.query.page as string) || 1;
    const limit = parseInt(req.query.limit as string) || 20;
    const etudiantId = req.query.etudiantId ? parseInt(req.query.etudiantId as string) : undefined;
    const mode = req.query.mode as string | undefined;

    const where: any = {};
    if (etudiantId) where.etudiantId = etudiantId;
    if (mode) where.modePaiement = mode;

    const total = await prisma.paiement.count({ where });
    const paiements = await prisma.paiement.findMany({
      where,
      include: { etudiant: true },
      skip: (page - 1) * limit,
      take: limit,
      orderBy: { datePaiement: 'desc' },
    });

    // Get KPIs
    const activeYear = await prisma.anneeScolaire.findFirst({ where: { isActive: true } });
    const now = new Date();
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);

    const monthlyTotal = await prisma.paiement.aggregate({
      where: {
        datePaiement: { gte: startOfMonth },
        etudiant: activeYear ? { anneeScolaireId: activeYear.id } : {},
      },
      _sum: { montant: true },
    });

    const enRetardCount = await prisma.echeanceMensuelle.count({
      where: { statut: 'EN_RETARD' },
    });

    const impayesAgg = await prisma.echeanceMensuelle.findMany({
      where: { statut: 'EN_RETARD' },
    });
    const montantImpayes = impayesAgg.reduce((sum, e) => sum + (e.montantDu - e.montantPaye), 0);

    const result = paiements.map(p => ({
      id: p.id,
      date: p.datePaiement.toLocaleDateString('fr-FR'),
      etudiant: `${p.etudiant.prenom} ${p.etudiant.nom}`,
      etudiantId: p.etudiantId,
      montant: p.montant,
      mode: p.modePaiement === 'ESPECES' ? 'Especes'
        : p.modePaiement === 'VIREMENT' ? 'Virement'
        : 'Cheque',
      statut: 'Paye',
      recu: p.recu,
    }));

    res.json({
      data: result,
      kpis: {
        totalMois: monthlyTotal._sum.montant || 0,
        enRetard: enRetardCount,
        montantImpayes,
      },
      pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Erreur serveur' });
  }
}

export async function create(req: Request, res: Response): Promise<void> {
  try {
    const { etudiantId, montant, modePaiement } = req.body;

    if (!etudiantId || !montant || !modePaiement) {
      res.status(400).json({ error: 'Tous les champs sont requis' });
      return;
    }

    const etudiant = await prisma.etudiant.findUnique({
      where: { id: etudiantId },
      include: { filiere: true },
    });

    if (!etudiant) {
      res.status(404).json({ error: 'Etudiant non trouve' });
      return;
    }

    // Create payment
    const paiement = await prisma.paiement.create({
      data: {
        etudiantId,
        montant,
        datePaiement: new Date(),
        modePaiement,
      },
    });

    // Update echeances
    let remainingAmount = montant;
    const echeancier = await prisma.echeancier.findFirst({
      where: { etudiantId },
      include: { echeances: { orderBy: { id: 'asc' } } },
    });

    if (echeancier) {
      for (const echeance of echeancier.echeances) {
        if (remainingAmount <= 0) break;
        if (echeance.statut === 'PAYE') continue;

        const due = echeance.montantDu - echeance.montantPaye;
        const payment = Math.min(remainingAmount, due);

        await prisma.echeanceMensuelle.update({
          where: { id: echeance.id },
          data: {
            montantPaye: echeance.montantPaye + payment,
            statut: echeance.montantPaye + payment >= echeance.montantDu ? 'PAYE' : echeance.statut,
            datePaiement: new Date(),
          },
        });

        remainingAmount -= payment;
      }
    }

    // Generate PDF receipt
    const receiptFilename = `recu-${paiement.id}-${Date.now()}.pdf`;
    const receiptPath = path.join(__dirname, '../../uploads', receiptFilename);

    await generateReceipt({
      id: paiement.id,
      etudiant: `${etudiant.prenom} ${etudiant.nom}`,
      cin: etudiant.cin,
      filiere: etudiant.filiere.name,
      montant,
      modePaiement,
      date: new Date(),
      outputPath: receiptPath,
    });

    // Update payment with receipt path
    await prisma.paiement.update({
      where: { id: paiement.id },
      data: { recu: receiptFilename },
    });

    res.status(201).json({
      ...paiement,
      recu: receiptFilename,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Erreur serveur' });
  }
}

export async function getEcheancier(req: Request, res: Response): Promise<void> {
  try {
    const etudiantId = parseInt(req.params.etudiantId);

    const echeancier = await prisma.echeancier.findFirst({
      where: { etudiantId },
      include: {
        echeances: { orderBy: { id: 'asc' } },
        etudiant: { include: { filiere: true } },
      },
    });

    if (!echeancier) {
      res.status(404).json({ error: 'Echeancier non trouve' });
      return;
    }

    res.json({
      montantTotal: echeancier.montantTotal,
      nombreMensualites: echeancier.nombreMensualites,
      echeances: echeancier.echeances.map(e => ({
        id: e.id,
        mois: e.mois,
        montantDu: e.montantDu,
        montantPaye: e.montantPaye,
        statut: e.statut,
        datePaiement: e.datePaiement,
      })),
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Erreur serveur' });
  }
}

export async function downloadRecu(req: Request, res: Response): Promise<void> {
  try {
    const id = parseInt(req.params.id);
    const paiement = await prisma.paiement.findUnique({ where: { id } });

    if (!paiement || !paiement.recu) {
      res.status(404).json({ error: 'Recu non trouve' });
      return;
    }

    const filePath = path.join(__dirname, '../../uploads', paiement.recu);
    res.download(filePath, paiement.recu);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Erreur serveur' });
  }
}
