import { useRef, useState, useEffect, useCallback } from 'react';
import { X, Download, Printer, ZoomIn, ZoomOut, RotateCcw } from 'lucide-react';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import logo from '../../assets/logo/logo.png'
import { Societe } from '@/types/societeType';
import { getSociete } from '@/store/features/gateways/selectors';
import { useAppSelector } from '@/store/hooks';

interface LigneDocument {
    article: string;
    designation?: string;
    quantite: number;
    prix_unitaire?: number;
    tva?: number;
    remise?: number;
    total_ht?: number;
}

export interface DocumentData {
    numero: string;
    type: 'devis' | 'facture' | 'bl';
    date: string;
    date_echeance?: string;
    client: {
        code: string;
        nom: string;
        adresse?: string;
        code_postal?: string;
        ville?: string;
        email?: string;
        telephone?: string;
    };
    reference_externe?: string;
    lignes: LigneDocument[];
    total_ht: number;
    total_tva: number;
    total_ttc: number;
    notes?: string;
}

interface PDFPreviewProps {
    open: boolean;
    onClose: () => void;
    data: DocumentData;
    entreprise?: {
        name: string;
        adresse: string;
        code_postal: string;
        ville: string;
        siret: string;
        tva_intra: string;
        telephone: string;
        email: string;
        logo?: string;
    };
}

export function PDFPreview({ open, onClose, data, entreprise }: PDFPreviewProps) {
    const documentRef = useRef<HTMLDivElement>(null);
    const [zoom, setZoom] = useState(100);
    const [isGenerating, setIsGenerating] = useState(false);
    const societe = useAppSelector(getSociete) as Societe;
    const ZOOM_MIN = 50;
    const ZOOM_MAX = 200;
    const ZOOM_STEP = 10;

    

    const defaultEntreprise = {
        name: "Bijou SA",
        adresse: "123 rue de la Joaillerie",
        code_postal: "75001",
        ville: "Paris",
        siret: "123 456 789 00012",
        tva_intra: "FR12345678901",
        telephone: "01 23 45 67 89",
        email: "contact@bijou.fr",
        ...entreprise
    };

    const getDocumentTitle = () => {
        switch (data.type) {
            case 'devis': return 'DEVIS';
            case 'facture': return 'FACTURE';
            case 'bl': return 'BON DE LIVRAISON';
            default: return 'DOCUMENT';
        }
    };

    const formatDate = (dateString: string) => {
        const date = new Date(dateString);
        return date.toLocaleDateString('fr-FR');
    };

    const formatCurrency = (amount: number) => {
        return amount.toFixed(2) + ' €';
    };

    const handleZoomIn = () => {
        setZoom(prev => Math.min(prev + ZOOM_STEP, ZOOM_MAX));
    };

    const handleZoomOut = () => {
        setZoom(prev => Math.max(prev - ZOOM_STEP, ZOOM_MIN));
    };

    const handleResetZoom = () => {
        setZoom(100);
    };

    useEffect(() => {
        if (!open) return;

        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape') {
                onClose();
            } else if (e.key === '+' || e.key === '=') {
                e.preventDefault();
                handleZoomIn();
            } else if (e.key === '-') {
                e.preventDefault();
                handleZoomOut();
            } else if (e.key === '0') {
                e.preventDefault();
                handleResetZoom();
            }
        };

        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [open, onClose]);

    const handleWheel = useCallback((e: React.WheelEvent) => {
        if (e.ctrlKey || e.metaKey) {
            e.preventDefault();
            if (e.deltaY < 0) {
                handleZoomIn();
            } else {
                handleZoomOut();
            }
        }
    }, []);

    const handleDownloadPDF = async () => {
        if (!documentRef.current || isGenerating) return;

        try {
            setIsGenerating(true);
            
            const originalTransform = documentRef.current.style.transform;
            documentRef.current.style.transform = 'scale(1)';

            const canvas = await html2canvas(documentRef.current, {
                scale: 2,
                useCORS: true,
                logging: false,
                backgroundColor: '#ffffff'
            });

            documentRef.current.style.transform = originalTransform;

            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF({
                orientation: 'portrait',
                unit: 'mm',
                format: 'a4'
            });

            const pdfWidth = pdf.internal.pageSize.getWidth();
            const pdfHeight = pdf.internal.pageSize.getHeight();
            const imgWidth = canvas.width;
            const imgHeight = canvas.height;
            const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);
            const imgX = (pdfWidth - imgWidth * ratio) / 2;
            const imgY = 0;

            pdf.addImage(imgData, 'PNG', imgX, imgY, imgWidth * ratio, imgHeight * ratio);
            pdf.save(`${data.type}_${data.numero}.pdf`);
        } catch (error) {
            console.error('Erreur lors de la génération du PDF:', error);
        } finally {
            setIsGenerating(false);
        }
    };

    const handlePrint = () => {
        window.print();
    };

    if (!open) return null;

    return (
        <>
            {/* Backdrop */}
            <div
                onClick={onClose}
                className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50"
            />

            {/* Slide Panel */}
            <div className="fixed inset-y-0 right-0 w-full max-w-4xl bg-[#525659] shadow-2xl z-50 flex flex-col">
                {/* Header Toolbar */}
                <div className="bg-[#323639] shadow-md px-6 py-3 flex items-center justify-between border-b border-gray-700">
                    <div className="flex items-center gap-4">
                        <button
                            onClick={onClose}
                            className="p-2 hover:bg-gray-700 rounded-lg transition-colors text-gray-300 hover:text-white"
                        >
                            <X className="w-5 h-5" />
                        </button>
                        <h2 className="font-medium text-gray-200 text-sm uppercase tracking-wider">
                            Aperçu PDF
                        </h2>
                    </div>

                    {/* Zoom Controls */}
                    <div className="flex items-center gap-2 bg-gray-700 rounded-lg p-1">
                        <button
                            onClick={handleZoomOut}
                            disabled={zoom <= ZOOM_MIN}
                            className="p-1.5 hover:bg-gray-600 rounded-md transition-colors disabled:opacity-40 text-gray-300 hover:text-white"
                        >
                            <ZoomOut className="w-4 h-4" />
                        </button>
                        
                        <button
                            onClick={handleResetZoom}
                            className="px-3 py-1 text-sm font-bold text-white hover:bg-gray-600 rounded-md min-w-[60px]"
                        >
                            {zoom}%
                        </button>
                        
                        <button
                            onClick={handleZoomIn}
                            disabled={zoom >= ZOOM_MAX}
                            className="p-1.5 hover:bg-gray-600 rounded-md transition-colors disabled:opacity-40 text-gray-300 hover:text-white"
                        >
                            <ZoomIn className="w-4 h-4" />
                        </button>

                        <div className="w-px h-6 bg-gray-600 mx-1" />

                        <button
                            onClick={handleResetZoom}
                            className="p-1.5 hover:bg-gray-600 rounded-md transition-colors text-gray-300 hover:text-white"
                        >
                            <RotateCcw className="w-4 h-4" />
                        </button>
                    </div>

                    {/* Action Buttons */}
                    <div className="flex items-center gap-2">
                        <button
                            onClick={handlePrint}
                            className="flex items-center gap-2 px-4 py-1.5 text-sm text-gray-300 hover:bg-gray-700 rounded-lg transition-colors hover:text-white"
                        >
                            <Printer className="w-4 h-4" />
                            <span className="hidden sm:inline">Imprimer</span>
                        </button>
                        <button
                            onClick={handleDownloadPDF}
                            disabled={isGenerating}
                             className="flex items-center gap-2 px-4 py-1.5 text-sm text-gray-300 hover:bg-gray-700 rounded-lg transition-colors hover:text-white"
                        >
                            <Download className="w-4 h-4" />
                            <span className="hidden sm:inline">{isGenerating ? 'Génération...' : 'Télécharger'}</span>
                        </button>
                    </div>
                </div>

                {/* Document Preview Container */}
                <div 
                    className="flex-1 overflow-auto p-8 flex justify-center items-start bg-[#525659]"
                    onWheel={handleWheel}
                >
                    <div
                        className="transition-all duration-200 ease-out"
                        style={{ 
                            width: `${zoom}%`,
                            minWidth: '50mm',
                        }}
                    >
                        <div
                            ref={documentRef}
                            className="bg-white shadow-2xl border border-gray-300"
                            style={{ 
                                aspectRatio: '1 / 1.314',
                                padding: '8%',
                                fontFamily: 'system-ui, -apple-system, sans-serif',
                            }}
                        >
                            {/* Header */}
                            <div className="flex justify-between items-start mb-12">
                                {/* Logo placeholder */}
                                <div><img src={logo} alt="" className='w-25 h-20'/></div>

                                {/* Document Info */}
                                <div className="text-right flex flex-col gap-2">
                                    <h1 className="text-3xl font-bold uppercase text-gray-900">
                                        {data.numero || 'BROUILLON'}
                                    </h1>
                                    <div className="text-sm text-gray-500 flex flex-col gap-1">
                                        <p>Date : {formatDate(data.date)}</p>
                                        <p>Validité : {formatDate(data.date_echeance || data.date)}</p>
                                        <p>Réf : {data.reference_externe || '—'}</p>
                                    </div>
                                </div>
                            </div>

                            {/* Client Info */}
                            <div className="flex justify-between gap-12 mb-16">
                                <div className="w-1/2">
                                    <p className="text-xs font-bold text-gray-400 uppercase mb-2">Émetteur</p>
                                    <div className="text-sm text-gray-800 font-medium">
                                        <p>{societe?.raison_sociale}</p>
                                        <p className="font-normal text-gray-600">{societe?.adresse}</p>
                                        <p className="font-normal text-gray-600">{societe?.code_postal} {societe?.ville}, {societe?.pays}</p>
                                        <p className="font-normal text-gray-600 mt-1">{societe?.email_societe}</p>
                                        <p className="font-normal text-gray-600 mt-1">Tel : +{societe?.telephone}</p>
                                    </div>
                                </div>
                                <div className="w-1/2 bg-gray-50 p-6 rounded-xl border border-gray-100">
                                    <p className="text-xs font-bold text-gray-400 uppercase mb-2">Destinataire</p>
                                    <div className="text-sm text-gray-900">
                                        <p className="font-bold text-sm mb-1">{data.client.nom || 'Client'}</p>
                                        <p className="text-gray-600">10 rue des Clients</p>
                                        <p className="text-gray-600">75001 Paris</p>
                                    </div>
                                </div>
                            </div>

                            {/* info list */}
                            <div  className="flex text-sm border-b border-gray-200 pb-2">
                                <div className="flex-1">
                                    <p className="font-bold">Désignation</p>
                                </div>
                                <div className="font-bold w-16 text-right">Qté</div>
                                <div className="font-bold w-24 text-right">
                                    Prix Unit.HT
                                </div>
                                <div className="font-bold w-16 text-right">Remise</div>
                                <div className="font-bold w-16 text-right">TVA</div>
                                <div className="font-bold w-24 text-right ">
                                    Montant HT
                                </div>
                            </div>

                            {/* Lines */}
                            <div className="flex-1 space-y-3 mb-8">
                                {data.lignes.length > 0 ? (
                                    data.lignes.map((ligne, i) => {
                                        const prixUnitaire = ligne.prix_unitaire ?? 0;
                                        const totalHT = ligne.total_ht ?? (ligne.quantite * prixUnitaire);

                                        return (
                                            <div key={i} className="flex text-sm border-b border-gray-200 pb-2">
                                                <div className="flex-1">
                                                    <p className="font-bold">{ligne.article}</p>
                                                    {ligne.designation && (
                                                        <p className="text-gray-600 text-xs">{ligne.designation}</p>
                                                    )}
                                                </div>
                                                <div className="w-16 text-right text-gray-600">{ligne.quantite}</div>
                                                <div className="w-24 text-right text-gray-600">
                                                    {formatCurrency(prixUnitaire)}
                                                </div>
                                                <div className="w-16 text-right text-gray-400">{ligne.remise}%</div>
                                                <div className="w-16 text-right text-gray-400">{ligne.tva}%</div>
                                                <div className="w-24 text-right font-medium">
                                                    {formatCurrency(totalHT)}
                                                </div>
                                            </div>
                                        );
                                    })
                                ) : (
                                    <div className="text-center text-gray-400 italic py-8">
                                        Aucune ligne
                                    </div>
                                )}
                            </div>

                            {/* Totals */}
                            <div className="flex justify-end mb-8">
                                <div className="w-64 space-y-2 text-sm">
                                    <div className="flex justify-between text-gray-600">
                                        <span>Total HT</span>
                                        <span>{formatCurrency(data.total_ht)}</span>
                                    </div>
                                    <div className="flex justify-between text-gray-600">
                                        <span>TVA (20%)</span>
                                        <span>{formatCurrency(data.total_tva)}</span>
                                    </div>
                                    <div className="flex justify-between border-t-2 border-[#2A6F4F] pt-2 font-bold text-base text-[#2A6F4F]">
                                        <span>Net à payer</span>
                                        <span>{formatCurrency(data.total_ttc)}</span>
                                    </div>
                                </div>
                            </div>

                            {/* Notes */}
                            {data.notes && (
                                <div className="mt-10 border-t border-gray-300 pt-4">
                                    <p className="text-xs font-bold uppercase text-gray-400 mb-2">
                                        Notes & Conditions
                                    </p>
                                    <p className="text-xs text-gray-600 whitespace-pre-wrap">
                                        {data.notes}
                                    </p>
                                </div>
                            )}

                            {/* Footer */}
                            <div className="mt-auto pt-8 text-center">
                                <p className="text-[10px] text-gray-400">Page 1 / 1</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}

export default PDFPreview;
