/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState, useEffect } from 'react';
import { motion } from 'motion/react';
import { Download, FileText, RefreshCcw, AlertCircle } from 'lucide-react';
import useSWR from 'swr';
import { postFetcher } from '../../lib/fetcher';
import { useAuth } from '../../contexts/AuthContext';
import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';
import logoSm from '../../assets/logo-sm.png';
import { PaginationControls } from '../../components/PaginationControls';
import axios from 'axios';

const isEligibleForRefund = (inv: any) => {
  if (inv.status !== 'paid' && inv.status !== 'Paid') return false;
  if (parseFloat(inv.amount) <= 0) return false;
  const d = inv.createdAt?.seconds 
    ? new Date(inv.createdAt.seconds * 1000) 
    : new Date(inv.createdAt || inv.date || Date.now());
  const daysDiff = (Date.now() - d.getTime()) / (1000 * 3600 * 24);
  return daysDiff <= 14;
};

const generatePdf = async (inv: any, userName: string) => {
  try {
    const doc = new jsPDF();

    // Load logo
    const img = new Image();
    img.src = logoSm.src;
    await new Promise((resolve) => {
      img.onload = resolve;
      img.onerror = resolve; // Continue even if logo fails
    });

    // Add Logo (top left)
    if (img.complete && img.naturalWidth > 0) {
      // scale logo width to 40px
      const ratio = img.naturalHeight / img.naturalWidth;
      doc.addImage(img, 'PNG', 14, 15, 40, 40 * ratio);
    } else {
      doc.setFontSize(22);
      doc.setFont('helvetica', 'bold');
      doc.text('AGENDIVO', 14, 25);
    }

    // Invoice Title
    doc.setFontSize(24);
    doc.setFont('helvetica', 'bold');
    doc.text('FACTURE', 140, 25);

    doc.setFontSize(10);
    doc.setFont('helvetica', 'normal');
    doc.text(`Facture N°: ${inv.number}`, 140, 32);
    const dateStr = inv.createdAt?.seconds
      ? new Date(inv.createdAt.seconds * 1000).toLocaleDateString('fr-FR')
      : new Date(inv.date || Date.now()).toLocaleDateString('fr-FR');
    doc.text(`Date: ${dateStr}`, 140, 38);

    // Company Details
    doc.setFontSize(10);
    doc.setFont('helvetica', 'bold');
    doc.text('Émetteur:', 14, 55);
    doc.setFont('helvetica', 'normal');
    doc.text('Agendivo SAAS', 14, 61);

    // Client Details
    doc.setFont('helvetica', 'bold');
    doc.text('Facturé à:', 140, 55);
    doc.setFont('helvetica', 'normal');

    let clientY = 61;
    doc.text(userName, 140, clientY); clientY += 6;

    // AutoTable for items
    autoTable(doc, {
      startY: 95,
      headStyles: { fillColor: [37, 99, 235], textColor: 255 }, // Blue 600
      head: [['Description', 'Quantité', 'Prix Unitaire', 'Total']],
      body: [
        [`Abonnement: Forfait ${inv.plan || 'Standard'}`, '1', `${inv.amount} €`, `${inv.amount} €`],
      ],
      theme: 'striped',
    });

    // Totals
    const finalY = (doc as any).lastAutoTable.finalY || 130;
    doc.setFont('helvetica', 'bold');
    doc.text(`Total HT: ${parseFloat(inv.amount).toFixed(2)} €`, 140, finalY + 10);
    doc.text(`TVA (0%): 0.00 €`, 140, finalY + 16);
    doc.setFontSize(12);
    doc.text(`Total TTC: ${parseFloat(inv.amount).toFixed(2)} €`, 140, finalY + 24);

    // Footer
    doc.setFontSize(9);
    doc.setFont('helvetica', 'normal');
    doc.setTextColor(150);
    doc.text('Merci pour votre confiance !', 105, 280, { align: 'center' });

    doc.save(`Facture_${inv.number}.pdf`);
  } catch (err) {
    console.error('Error generating PDF', err);
  }
};

export const Invoices = () => {
  const { currentUser } = useAuth();
  const [currentPage, setCurrentPage] = useState(1);
  const ITEMS_PER_PAGE = 5;
  const [refundModalInvoice, setRefundModalInvoice] = useState<any>(null);
  const [refundLoading, setRefundLoading] = useState(false);
  const [refundError, setRefundError] = useState<string | null>(null);
  const [refundSuccess, setRefundSuccess] = useState<string | null>(null);

  const { data: invoicesData, isLoading: invoicesLoading } = useSWR(
    currentUser ? ['/api/db/query', { collection: 'invoices', conditions: [{ field: 'userId', op: '==', value: currentUser.uid }] }] : null,
    postFetcher
  );

  const loading = invoicesLoading;
  const invoices = invoicesData || [];

  const totalItems = invoices.length;
  const totalPages = Math.ceil(totalItems / ITEMS_PER_PAGE);

  useEffect(() => {
    if (currentPage > totalPages && totalPages > 0) {
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setCurrentPage(totalPages);
    }
  }, [totalPages, currentPage]);

  const paginatedInvoices = invoices.slice(
    (currentPage - 1) * ITEMS_PER_PAGE,
    currentPage * ITEMS_PER_PAGE
  );

  const handleRequestRefund = async () => {
    if (!refundModalInvoice) return;
    setRefundLoading(true);
    setRefundError(null);
    setRefundSuccess(null);

    try {
      const res = await axios.post('/api/billing/request-refund', { invoiceId: refundModalInvoice.id });
      setRefundSuccess(res.data.message);
    } catch (err: any) {
      setRefundError(err.response?.data?.message || 'Erreur lors de la demande de remboursement.');
    } finally {
      setRefundLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="bg-white dark:bg-slate-900 p-12 rounded-[2.5rem] border border-slate-100 dark:border-slate-800 shadow-sm text-center">
        <div className="w-12 h-12 border-4 border-blue-600/30 border-t-blue-600 rounded-full animate-spin mx-auto mb-4" />
      </div>
    );
  }

  return (
    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="bg-white dark:bg-slate-900 rounded-[2.5rem] p-8 border border-slate-100 dark:border-slate-800 shadow-sm">
      <div className="flex items-center gap-4 mb-6">
        <div className="p-3 bg-blue-50 dark:bg-blue-900/30 rounded-2xl">
          <FileText className="w-6 h-6 text-blue-600" />
        </div>
        <h2 className="text-2xl font-black text-slate-900 dark:text-white">Historique des factures</h2>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-left border-collapse">
          <thead>
            <tr className="border-b border-slate-200 dark:border-slate-800">
              <th className="pb-4 font-bold text-slate-400 text-sm uppercase tracking-widest">Facture</th>
              <th className="pb-4 font-bold text-slate-400 text-sm uppercase tracking-widest">Date</th>
              <th className="pb-4 font-bold text-slate-400 text-sm uppercase tracking-widest">Forfait</th>
              <th className="pb-4 font-bold text-slate-400 text-sm uppercase tracking-widest">Montant</th>
              <th className="pb-4 font-bold text-slate-400 text-sm uppercase tracking-widest">Statut</th>
              <th className="pb-4 font-bold text-slate-400 text-sm uppercase tracking-widest text-right">Action</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100 dark:divide-slate-800">

            {(paginatedInvoices || []).map((inv: any) => (
              <tr key={inv.id}>
                <td className="py-5 font-mono text-sm text-slate-900 dark:text-white">{inv.number}</td>
                <td className="py-5 font-medium text-slate-700 dark:text-slate-300">
                  {inv.createdAt?.seconds ? new Date(inv.createdAt.seconds * 1000).toLocaleDateString() : String(inv.date || '')}
                </td>
                <td className="py-5 font-medium text-slate-700 dark:text-slate-300">{inv.plan}</td>
                <td className="py-5 font-black text-slate-900 dark:text-white">{inv.amount}€</td>
                <td className="py-5">
                  <span className="bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 px-3 py-1 rounded-lg text-xs font-bold uppercase tracking-wider">{inv.status}</span>
                </td>
                <td className="py-5 text-right space-x-2">
                  {isEligibleForRefund(inv) && (
                    <button 
                      onClick={() => { setRefundModalInvoice(inv); setRefundError(null); setRefundSuccess(null); }} 
                      className="p-2 hover:bg-orange-100 dark:hover:bg-orange-900/30 rounded-lg text-orange-400 hover:text-orange-600 transition-colors inline-block"
                      title="Demander un remboursement"
                    >
                      <RefreshCcw className="w-5 h-5" />
                    </button>
                  )}
                  <button onClick={() => generatePdf(inv, currentUser?.displayName || currentUser?.email || 'Client')} className="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-lg text-slate-400 hover:text-blue-600 transition-colors inline-block" title="Télécharger la facture">
                    <Download className="w-5 h-5" />
                  </button>
                </td>
              </tr>
            ))}
            {invoices.length === 0 && (
              <tr>
                <td colSpan={6} className="py-8 text-center text-slate-500">Aucune facture disponible.</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
      <PaginationControls
        currentPage={currentPage}
        setCurrentPage={setCurrentPage}
        totalItems={totalItems}
        itemsPerPage={ITEMS_PER_PAGE}
      />

      {/* Refund Modal */}
      {refundModalInvoice && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm">
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-white dark:bg-slate-900 rounded-[2.5rem] p-8 max-w-md w-full border border-slate-100 dark:border-slate-800 shadow-2xl relative overflow-hidden"
          >
            <h3 className="text-2xl font-black text-slate-900 dark:text-white mb-4">Demande de remboursement</h3>
            
            {refundSuccess ? (
              <div className="bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400 p-4 rounded-2xl mb-6">
                <p className="font-bold">{refundSuccess}</p>
              </div>
            ) : refundError ? (
              <div className="bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-400 p-4 rounded-2xl mb-6">
                <p className="font-bold mb-2 flex items-center gap-2"><AlertCircle className="w-5 h-5" /> Non éligible</p>
                <p className="text-sm">{refundError}</p>
              </div>
            ) : (
              <p className="text-slate-600 dark:text-slate-400 font-medium mb-6">
                Vous êtes sur le point de demander le remboursement de la facture <strong>{refundModalInvoice.number}</strong> ({refundModalInvoice.amount}€). 
                Veuillez noter que si vous avez déjà bénéficié d&apos;une démo gratuite de 14 jours, vous ne serez pas éligible. Confirmez-vous cette demande ?
              </p>
            )}

            <div className="flex justify-end gap-3">
              <button
                onClick={() => setRefundModalInvoice(null)}
                className="px-6 py-3 rounded-xl font-bold text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
              >
                {refundSuccess ? 'Fermer' : 'Annuler'}
              </button>
              {!refundSuccess && !refundError && (
                <button
                  onClick={handleRequestRefund}
                  disabled={refundLoading}
                  className="px-6 py-3 rounded-xl font-bold text-white bg-orange-500 hover:bg-orange-600 disabled:opacity-50 transition-colors flex items-center gap-2"
                >
                  {refundLoading ? <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <RefreshCcw className="w-5 h-5" />}
                  Confirmer la demande
                </button>
              )}
            </div>
          </motion.div>
        </div>
      )}

    </motion.div>
  );
};
