'use client';
export const dynamic = 'force-dynamic';


import React, { useState, useEffect, useRef } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Card } from 'primereact/card';
import { Button } from 'primereact/button';
import { Tag } from 'primereact/tag';
import { Divider } from 'primereact/divider';
import { Toast } from 'primereact/toast';
import { ProgressSpinner } from 'primereact/progressspinner';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Timeline } from 'primereact/timeline';
import { Badge } from 'primereact/badge';
import { Toolbar } from 'primereact/toolbar';
import { Menu } from 'primereact/menu';
import { ProgressBar } from 'primereact/progressbar';
import { factureService } from '../../../../services/api';
import { formatDate, formatCurrency } from '../../../../utils/formatters';
import type { Facture } from '../../../../types/btp';
import { StatutFacture } from '../../../../types/btp';

const FactureDetailPage = () => {
    const params = useParams();
    const router = useRouter();
    const toast = useRef<Toast>(null);
    const menuRef = useRef<Menu>(null);
    
    const [facture, setFacture] = useState<Facture | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const factureId = params.id as string;

    useEffect(() => {
        loadFacture();
    }, [factureId]);

    const loadFacture = async () => {
        try {
            setLoading(true);
            const response = await factureService.getById(factureId);
            setFacture(response);
        } catch (error) {
            console.error('Erreur lors du chargement de la facture:', error);
            setError('Impossible de charger la facture');
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger la facture'
            });
        } finally {
            setLoading(false);
        }
    };

    const getStatutSeverity = (statut: string) => {
        switch (statut) {
            case 'PAYEE': return 'success';
            case 'EN_RETARD': return 'danger';
            case 'PARTIELLEMENT_PAYEE': return 'warning';
            case 'ENVOYEE': return 'info';
            case 'BROUILLON': return 'secondary';
            default: return 'info';
        }
    };

    const getTypeSeverity = (type: string) => {
        switch (type) {
            case 'FACTURE': return 'primary';
            case 'ACOMPTE': return 'info';
            case 'SITUATION': return 'warning';
            case 'SOLDE': return 'success';
            default: return 'secondary';
        }
    };

    const menuItems = [
        {
            label: 'Modifier',
            icon: 'pi pi-pencil',
            command: () => router.push(`/factures/${factureId}/edit`)
        },
        {
            label: 'Dupliquer',
            icon: 'pi pi-copy',
            command: () => router.push(`/factures/${factureId}/duplicate`)
        },
        {
            separator: true
        },
        {
            label: 'Marquer comme payée',
            icon: 'pi pi-check',
            command: () => handleMarkAsPaid(),
            disabled: facture?.statut === 'PAYEE'
        },
        {
            label: 'Enregistrer paiement partiel',
            icon: 'pi pi-money-bill',
            command: () => handlePartialPayment()
        },
        {
            separator: true
        },
        {
            label: 'Imprimer',
            icon: 'pi pi-print',
            command: () => window.print()
        },
        {
            label: 'Télécharger PDF',
            icon: 'pi pi-download',
            command: () => handleDownloadPDF()
        },
        {
            label: 'Envoyer par email',
            icon: 'pi pi-send',
            command: () => handleSendEmail()
        },
        {
            separator: true
        },
        {
            label: 'Supprimer',
            icon: 'pi pi-trash',
            className: 'text-red-500',
            command: () => handleDelete()
        }
    ];

    const handleMarkAsPaid = async () => {
        try {
            await factureService.update(factureId, { statut: StatutFacture.PAYEE });
            loadFacture();
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Facture marquée comme payée'
            });
        } catch (error) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors de la mise à jour'
            });
        }
    };

    const handlePartialPayment = () => {
        // TODO: Ouvrir dialog pour paiement partiel
        toast.current?.show({
            severity: 'info',
            summary: 'Info',
            detail: 'Fonctionnalité de paiement partiel en cours de développement'
        });
    };

    const handleDownloadPDF = async () => {
        try {
            // TODO: Implémenter le téléchargement PDF
            toast.current?.show({
                severity: 'info',
                summary: 'Info',
                detail: 'Téléchargement PDF en cours de développement'
            });
        } catch (error) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors du téléchargement'
            });
        }
    };

    const handleSendEmail = () => {
        // TODO: Ouvrir dialog d'envoi email
        toast.current?.show({
            severity: 'info',
            summary: 'Info',
            detail: 'Envoi par email en cours de développement'
        });
    };

    const handleDelete = async () => {
        try {
            await factureService.delete(factureId);
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Facture supprimée avec succès'
            });
            router.push('/factures');
        } catch (error) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors de la suppression'
            });
        }
    };

    const calculateProgress = () => {
        if (!facture) return 0;
        return (facture.montantPaye || 0) / facture.montantTTC * 100;
    };

    const toolbarStartTemplate = () => (
        <div className="flex align-items-center gap-2">
            <Button
                icon="pi pi-arrow-left"
                label="Retour"
                className="p-button-outlined"
                onClick={() => router.push('/factures')}
            />
        </div>
    );

    const toolbarEndTemplate = () => (
        <div className="flex align-items-center gap-2">
            {facture?.statut !== 'PAYEE' && (
                <Button
                    label="Marquer payée"
                    icon="pi pi-check"
                    className="p-button-success"
                    onClick={handleMarkAsPaid}
                />
            )}
            <Button
                icon="pi pi-ellipsis-v"
                className="p-button-text"
                onClick={(e) => menuRef.current?.toggle(e)}
            />
        </div>
    );

    if (loading) {
        return (
            <div className="flex justify-content-center align-items-center min-h-screen">
                <ProgressSpinner />
            </div>
        );
    }

    if (error || !facture) {
        return (
            <div className="flex justify-content-center align-items-center min-h-screen">
                <div className="text-center">
                    <i className="pi pi-exclamation-triangle text-6xl text-orange-500 mb-3"></i>
                    <h3>Facture introuvable</h3>
                    <p className="text-600 mb-4">{error || 'La facture demandée n\'existe pas'}</p>
                    <Button
                        label="Retour à la liste"
                        icon="pi pi-arrow-left"
                        onClick={() => router.push('/factures')}
                    />
                </div>
            </div>
        );
    }

    return (
        <div className="grid">
            <Toast ref={toast} />
            <Menu ref={menuRef} model={menuItems} popup />
            
            <div className="col-12">
                <Toolbar start={toolbarStartTemplate} end={toolbarEndTemplate} />
            </div>

            {/* En-tête de la facture */}
            <div className="col-12">
                <Card>
                    <div className="flex justify-content-between align-items-start mb-4">
                        <div>
                            <h2 className="text-2xl font-bold mb-2">Facture #{facture.numero}</h2>
                            <p className="text-600 mb-3">{facture.objet}</p>
                            <div className="flex gap-2 mb-2">
                                <Tag
                                    value={facture.statut}
                                    severity={getStatutSeverity(facture.statut) as any}
                                />
                                <Tag
                                    value={facture.typeFacture}
                                    severity={getTypeSeverity(facture.typeFacture) as any}
                                />
                            </div>
                        </div>
                        <div className="text-right">
                            <div className="text-3xl font-bold text-primary mb-2">
                                {formatCurrency(facture.montantTTC)}
                            </div>
                            <div className="text-sm text-600">
                                HT: {formatCurrency(facture.montantHT)}
                            </div>
                            {facture.montantPaye && facture.montantPaye > 0 && (
                                <div className="text-sm text-green-600 font-semibold">
                                    Payé: {formatCurrency(facture.montantPaye)}
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Barre de progression du paiement */}
                    {facture.montantPaye && facture.montantPaye > 0 && (
                        <div className="mb-4">
                            <div className="flex justify-content-between align-items-center mb-2">
                                <span className="font-semibold">Progression du paiement</span>
                                <span className="text-sm">{Math.round(calculateProgress())}%</span>
                            </div>
                            <ProgressBar 
                                value={calculateProgress()} 
                                className="mb-2"
                                style={{ height: '8px' }}
                            />
                            <div className="flex justify-content-between text-sm text-600">
                                <span>Payé: {formatCurrency(facture.montantPaye)}</span>
                                <span>Restant: {formatCurrency(facture.montantTTC - facture.montantPaye)}</span>
                            </div>
                        </div>
                    )}

                    <div className="grid">
                        <div className="col-12 md:col-6">
                            <h5>Informations générales</h5>
                            <div className="field">
                                <label className="font-semibold">Date d'émission:</label>
                                <p>{formatDate(facture.dateEmission)}</p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">Date d'échéance:</label>
                                <p className={new Date(facture.dateEcheance) < new Date() && facture.statut !== 'PAYEE' ? 'text-red-500 font-semibold' : ''}>
                                    {formatDate(facture.dateEcheance)}
                                </p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">Client:</label>
                                <p>{typeof facture.client === 'string' ? facture.client : facture.client?.nom}</p>
                            </div>
                            {facture.devis && (
                                <div className="field">
                                    <label className="font-semibold">Devis source:</label>
                                    <p>
                                        <Button
                                            label={`Devis #${typeof facture.devis === 'string' ? facture.devis : facture.devis?.numero}`}
                                            className="p-button-link p-0"
                                            onClick={() => router.push(`/devis/${typeof facture.devis === 'string' ? facture.devis : facture.devis?.id}`)}
                                        />
                                    </p>
                                </div>
                            )}
                        </div>
                        <div className="col-12 md:col-6">
                            <h5>Détails financiers</h5>
                            <div className="field">
                                <label className="font-semibold">Montant HT:</label>
                                <p>{formatCurrency(facture.montantHT)}</p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">TVA ({facture.tauxTVA}%):</label>
                                <p>{formatCurrency(facture.montantTTC - facture.montantHT)}</p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">Montant TTC:</label>
                                <p className="text-xl font-bold text-primary">{formatCurrency(facture.montantTTC)}</p>
                            </div>
                            {facture.montantPaye && (
                                <div className="field">
                                    <label className="font-semibold">Montant payé:</label>
                                    <p className="text-green-600 font-semibold">{formatCurrency(facture.montantPaye)}</p>
                                </div>
                            )}
                        </div>
                    </div>

                    {facture.description && (
                        <>
                            <Divider />
                            <div>
                                <h5>Description</h5>
                                <p className="line-height-3">{facture.description}</p>
                            </div>
                        </>
                    )}
                </Card>
            </div>

            {/* Lignes de la facture */}
            {facture.lignes && facture.lignes.length > 0 && (
                <div className="col-12">
                    <Card title="Détail des prestations">
                        <DataTable value={facture.lignes} responsiveLayout="scroll">
                            <Column field="designation" header="Désignation" />
                            <Column 
                                field="quantite" 
                                header="Quantité" 
                                style={{ width: '100px' }}
                                body={(rowData) => rowData.quantite?.toLocaleString('fr-FR')}
                            />
                            <Column field="unite" header="Unité" style={{ width: '80px' }} />
                            <Column 
                                field="prixUnitaire" 
                                header="Prix unitaire" 
                                style={{ width: '120px' }}
                                body={(rowData) => formatCurrency(rowData.prixUnitaire)}
                            />
                            <Column 
                                field="montantHT" 
                                header="Montant HT" 
                                style={{ width: '120px' }}
                                body={(rowData) => formatCurrency(rowData.montantHT)}
                            />
                        </DataTable>
                    </Card>
                </div>
            )}

            {/* Historique des paiements */}
            <div className="col-12">
                <Card title="Historique">
                    <Timeline 
                        value={[
                            {
                                status: 'Créée',
                                date: facture.dateEmission,
                                icon: 'pi pi-plus',
                                color: '#9C27B0'
                            },
                            ...(facture.statut === 'ENVOYEE' || facture.statut === 'PAYEE' ? [{
                                status: 'Envoyée',
                                date: new Date(),
                                icon: 'pi pi-send',
                                color: '#2196F3'
                            }] : []),
                            ...(facture.montantPaye && facture.montantPaye > 0 ? [{
                                status: facture.statut === 'PAYEE' ? 'Payée intégralement' : 'Paiement partiel',
                                date: new Date(),
                                icon: 'pi pi-money-bill',
                                color: facture.statut === 'PAYEE' ? '#4CAF50' : '#FF9800',
                                details: `Montant: ${formatCurrency(facture.montantPaye)}`
                            }] : []),
                            ...(new Date(facture.dateEcheance) < new Date() && facture.statut !== 'PAYEE' ? [{
                                status: 'Échue',
                                date: facture.dateEcheance,
                                icon: 'pi pi-exclamation-triangle',
                                color: '#F44336'
                            }] : [])
                        ]}
                        opposite={(item) => formatDate(item.date)}
                        content={(item) => (
                            <div className="flex align-items-center">
                                <Badge value={item.status} style={{ backgroundColor: item.color }} />
                                {item.details && (
                                    <div className="ml-2 text-sm text-600">{item.details}</div>
                                )}
                            </div>
                        )}
                    />
                </Card>
            </div>
        </div>
    );
};

export default FactureDetailPage;
