'use client';

import React, { useState, useEffect, useRef } from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext';
import { Card } from 'primereact/card';
import { Toast } from 'primereact/toast';
import { Toolbar } from 'primereact/toolbar';
import { Tag } from 'primereact/tag';
import { Dialog } from 'primereact/dialog';
import { Calendar } from 'primereact/calendar';
import { InputTextarea } from 'primereact/inputtextarea';
import { Dropdown } from 'primereact/dropdown';
import { Chip } from 'primereact/chip';
import { factureService } from '../../../../services/api';
import { formatDate, formatCurrency } from '../../../../utils/formatters';
import type { Facture } from '../../../../types/btp';
import { StatutFacture } from '../../../../types/btp';
import { 
    ActionButtonGroup, 
    ViewButton, 
    EditButton, 
    DeleteButton,
    ActionButton
} from '../../../../components/ui/ActionButton';

const FacturesImpayeesPage = () => {
    const [factures, setFactures] = useState<Facture[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [selectedFactures, setSelectedFactures] = useState<Facture[]>([]);
    const [actionDialog, setActionDialog] = useState(false);
    const [selectedFacture, setSelectedFacture] = useState<Facture | null>(null);
    const [actionType, setActionType] = useState<'payment' | 'reminder' | 'schedule'>('payment');
    const [paymentData, setPaymentData] = useState({
        datePaiement: new Date(),
        montantPaye: 0,
        modePaiement: '',
        notes: ''
    });
    const [reminderData, setReminderData] = useState({
        type: 'EMAIL',
        message: ''
    });
    const toast = useRef<Toast>(null);
    const dt = useRef<DataTable<Facture[]>>(null);

    const paymentMethods = [
        { label: 'Virement bancaire', value: 'VIREMENT' },
        { label: 'Chèque', value: 'CHEQUE' },
        { label: 'Espèces', value: 'ESPECES' },
        { label: 'Carte bancaire', value: 'CB' },
        { label: 'Prélèvement', value: 'PRELEVEMENT' }
    ];

    const reminderTypes = [
        { label: 'Email', value: 'EMAIL' },
        { label: 'Courrier', value: 'COURRIER' },
        { label: 'Téléphone', value: 'TELEPHONE' },
        { label: 'SMS', value: 'SMS' }
    ];

    useEffect(() => {
        loadFactures();
    }, []);

    const loadFactures = async () => {
        try {
            setLoading(true);
            const data = await factureService.getAll();
            // Filtrer les factures impayées (émises ou envoyées mais pas payées)
            const facturesImpayees = data.filter(facture =>
                (facture.statut === StatutFacture.ENVOYEE || facture.statut === StatutFacture.BROUILLON) &&
                !facture.datePaiement
            );
            setFactures(facturesImpayees);
        } catch (error) {
            console.error('Erreur lors du chargement des factures:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger les factures impayées',
                life: 3000
            });
        } finally {
            setLoading(false);
        }
    };

    const getDaysOverdue = (dateEcheance: string | Date) => {
        const today = new Date();
        const dueDate = new Date(dateEcheance);
        const diffTime = today.getTime() - dueDate.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        return Math.max(0, diffDays);
    };

    const isOverdue = (dateEcheance: string | Date) => {
        return getDaysOverdue(dateEcheance) > 0;
    };

    const getUrgencyLevel = (dateEcheance: string | Date) => {
        const days = getDaysOverdue(dateEcheance);
        if (days === 0) return { level: 'À ÉCHÉANCE', color: 'orange', severity: 'warning' as const };
        if (days <= 7) return { level: 'LÉGER RETARD', color: 'orange', severity: 'warning' as const };
        if (days <= 30) return { level: 'RETARD', color: 'red', severity: 'danger' as const };
        return { level: 'RETARD IMPORTANT', color: 'darkred', severity: 'danger' as const };
    };

    const recordPayment = (facture: Facture) => {
        setSelectedFacture(facture);
        setActionType('payment');
        setPaymentData({
            datePaiement: new Date(),
            montantPaye: facture.montantTTC || 0,
            modePaiement: '',
            notes: ''
        });
        setActionDialog(true);
    };

    const sendReminder = (facture: Facture) => {
        setSelectedFacture(facture);
        setActionType('reminder');
        setReminderData({
            type: 'EMAIL',
            message: `Madame, Monsieur,\n\nNous vous rappelons que la facture ${facture.numero} d'un montant de ${formatCurrency(facture.montantTTC || 0)} arrive à échéance le ${formatDate(facture.dateEcheance)}.\n\nMerci de bien vouloir procéder au règlement dans les plus brefs délais.\n\nCordialement`
        });
        setActionDialog(true);
    };

    const schedulePayment = (facture: Facture) => {
        setSelectedFacture(facture);
        setActionType('schedule');
        setActionDialog(true);
    };

    const handleAction = async () => {
        if (!selectedFacture) return;

        try {
            let message = '';

            switch (actionType) {
                case 'payment':
                    // TODO: Implémenter l'enregistrement de paiement
                    console.log('Enregistrement de paiement:', {
                        facture: selectedFacture,
                        paymentData
                    });
                    // Retirer de la liste des impayées
                    setFactures(prev => prev.filter(f => f.id !== selectedFacture.id));
                    message = 'Paiement enregistré avec succès';
                    break;
                    
                case 'reminder':
                    // TODO: Implémenter l'envoi de relance
                    console.log('Envoi de relance:', {
                        facture: selectedFacture,
                        reminderData
                    });
                    message = 'Relance envoyée au client';
                    break;
                    
                case 'schedule':
                    // TODO: Implémenter la planification de paiement
                    console.log('Planification de paiement:', selectedFacture);
                    message = 'Échéancier de paiement programmé';
                    break;
            }

            setActionDialog(false);
            
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: `${message} (simulation)`,
                life: 3000
            });
        } catch (error) {
            console.error('Erreur lors de l\'action:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible d\'effectuer l\'action',
                life: 3000
            });
        }
    };

    const exportCSV = () => {
        dt.current?.exportCSV();
    };

    const bulkReminder = async () => {
        if (selectedFactures.length === 0) {
            toast.current?.show({
                severity: 'warn',
                summary: 'Attention',
                detail: 'Veuillez sélectionner au moins une facture',
                life: 3000
            });
            return;
        }

        // Simulation d'envoi de relances en lot
        console.log('Envoi de relances en lot à', selectedFactures.length, 'factures');
        
        setSelectedFactures([]);
        toast.current?.show({
            severity: 'success',
            summary: 'Succès',
            detail: `${selectedFactures.length} relance(s) envoyée(s) (simulation)`,
            life: 3000
        });
    };

    const generateOverdueReport = () => {
        const totalOverdue = factures.reduce((sum, f) => sum + (f.montantTTC || 0), 0);
        const severelyOverdue = factures.filter(f => getDaysOverdue(f.dateEcheance) > 30);
        const recentOverdue = factures.filter(f => getDaysOverdue(f.dateEcheance) <= 7);
        
        const report = `
=== RAPPORT FACTURES IMPAYÉES ===
Date du rapport: ${new Date().toLocaleDateString('fr-FR')}

STATISTIQUES GÉNÉRALES:
- Nombre total de factures impayées: ${factures.length}
- Montant total impayé: ${formatCurrency(totalOverdue)}
- Montant moyen par facture: ${formatCurrency(totalOverdue / (factures.length || 1))}

RÉPARTITION PAR GRAVITÉ:
- Retard léger (≤7 jours): ${recentOverdue.length} factures, ${formatCurrency(recentOverdue.reduce((sum, f) => sum + (f.montantTTC || 0), 0))}
- Retard important (>30 jours): ${severelyOverdue.length} factures, ${formatCurrency(severelyOverdue.reduce((sum, f) => sum + (f.montantTTC || 0), 0))}

FACTURES EN RETARD CRITIQUE (>30 jours):
${severelyOverdue.map(f => `
- ${f.numero} - ${f.objet}
  Client: ${f.client ? `${f.client.prenom} ${f.client.nom}` : 'N/A'}
  Montant: ${formatCurrency(f.montantTTC || 0)}
  Retard: ${getDaysOverdue(f.dateEcheance)} jours
  Échéance: ${formatDate(f.dateEcheance)}
`).join('')}

ANALYSE PAR CLIENT:
${getClientOverdueAnalysis()}

RECOMMANDATIONS:
- Relancer immédiatement les factures en retard critique
- Mettre en place des échéanciers pour les gros montants
- Examiner les conditions de paiement accordées
- Considérer un contentieux pour les retards >60 jours
        `;
        
        const blob = new Blob([report], { type: 'text/plain;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `rapport_factures_impayees_${new Date().toISOString().split('T')[0]}.txt`;
        link.click();
        
        toast.current?.show({
            severity: 'success',
            summary: 'Rapport généré',
            detail: 'Le rapport d\'impayés a été téléchargé',
            life: 3000
        });
    };

    const getClientOverdueAnalysis = () => {
        const clientStats = {};
        factures.forEach(f => {
            if (f.client) {
                const clientKey = `${f.client.prenom} ${f.client.nom}`;
                if (!clientStats[clientKey]) {
                    clientStats[clientKey] = { count: 0, value: 0, maxDays: 0 };
                }
                clientStats[clientKey].count++;
                clientStats[clientKey].value += f.montantTTC || 0;
                clientStats[clientKey].maxDays = Math.max(clientStats[clientKey].maxDays, getDaysOverdue(f.dateEcheance));
            }
        });
        
        return Object.entries(clientStats)
            .sort((a: [string, any], b: [string, any]) => b[1].value - a[1].value)
            .slice(0, 5)
            .map(([client, data]: [string, any]) => `- ${client}: ${data.count} factures, ${formatCurrency(data.value)}, retard max: ${data.maxDays} jours`)
            .join('\n');
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="my-2 flex gap-2">
                <h5 className="m-0 flex align-items-center text-red-600">
                    <i className="pi pi-exclamation-triangle mr-2"></i>
                    Factures impayées ({factures.length})
                </h5>
                <Chip 
                    label={`Total impayé: ${formatCurrency(factures.reduce((sum, f) => sum + (f.montantTTC || 0), 0))}`} 
                    className="bg-red-100 text-red-800"
                />
                <Button 
                    label="Relancer sélection" 
                    icon="pi pi-send" 
                    severity="warning" 
                    size="small"
                    onClick={bulkReminder}
                    disabled={selectedFactures.length === 0}
                />
                <Button 
                    label="Rapport d'impayés" 
                    icon="pi pi-chart-line" 
                    severity="danger" 
                    size="small"
                    onClick={generateOverdueReport}
                />
            </div>
        );
    };

    const rightToolbarTemplate = () => {
        return (
            <Button 
                label="Exporter" 
                icon="pi pi-upload" 
                severity="help" 
                onClick={exportCSV} 
            />
        );
    };

    const actionBodyTemplate = (rowData: Facture) => {
        return (
            <ActionButtonGroup>
                <ActionButton
                    icon="pi pi-check-circle"
                    color="green"
                    tooltip="Enregistrer le paiement"
                    onClick={() => recordPayment(rowData)}
                />
                <ActionButton
                    icon="pi pi-send"
                    color="orange"
                    tooltip="Envoyer une relance"
                    onClick={() => sendReminder(rowData)}
                />
                <ActionButton
                    icon="pi pi-calendar"
                    color="blue"
                    tooltip="Planifier un échéancier"
                    onClick={() => schedulePayment(rowData)}
                />
                <ViewButton 
                    tooltip="Voir détails"
                    onClick={() => {
                        toast.current?.show({
                            severity: 'info',
                            summary: 'Info',
                            detail: `Détails de la facture ${rowData.numero}`,
                            life: 3000
                        });
                    }}
                />
            </ActionButtonGroup>
        );
    };

    const statusBodyTemplate = (rowData: Facture) => {
        const urgency = getUrgencyLevel(rowData.dateEcheance);
        const overdue = isOverdue(rowData.dateEcheance);
        
        return (
            <div className="flex align-items-center gap-2">
                <Tag value="Impayée" severity="danger" />
                {overdue && (
                    <Tag 
                        value={urgency.level} 
                        severity={urgency.severity}
                    />
                )}
            </div>
        );
    };

    const dueDateBodyTemplate = (rowData: Facture) => {
        const days = getDaysOverdue(rowData.dateEcheance);
        const overdue = isOverdue(rowData.dateEcheance);
        const urgency = getUrgencyLevel(rowData.dateEcheance);
        
        return (
            <div className={overdue ? 'text-red-600 font-bold' : 'text-orange-600'}>
                <div>{formatDate(rowData.dateEcheance)}</div>
                <small>
                    {days === 0 ? 'Échéance aujourd\'hui' : 
                     overdue ? `Retard de ${days} jour${days > 1 ? 's' : ''}` :
                     `Échéance dans ${Math.abs(days)} jour${Math.abs(days) > 1 ? 's' : ''}`}
                </small>
                {overdue && <i className="pi pi-exclamation-triangle ml-1 text-red-500"></i>}
            </div>
        );
    };

    const clientBodyTemplate = (rowData: Facture) => {
        if (!rowData.client) return '';
        return `${rowData.client.prenom} ${rowData.client.nom}`;
    };

    const amountBodyTemplate = (rowData: Facture) => {
        const amount = rowData.montantTTC || 0;
        let severity = 'secondary';
        
        if (amount > 10000) {
            severity = 'danger';
        } else if (amount > 5000) {
            severity = 'warning';
        } else if (amount > 1000) {
            severity = 'info';
        }
        
        return (
            <div>
                <div className="font-bold">{formatCurrency(amount)}</div>
                <Tag 
                    value={amount > 10000 ? 'Prioritaire' : amount > 5000 ? 'Important' : 'Standard'} 
                    severity={severity as any} 
                    className="text-xs mt-1" 
                />
            </div>
        );
    };

    const header = (
        <div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
            <h5 className="m-0">Factures impayées - Suivi des encaissements</h5>
            <span className="block mt-2 md:mt-0 p-input-icon-left">
                <i className="pi pi-search" />
                <InputText 
                    type="search" 
                    placeholder="Rechercher..." 
                    onInput={(e) => setGlobalFilter(e.currentTarget.value)} 
                />
            </span>
        </div>
    );

    const actionDialogFooter = (
        <>
            <Button 
                label="Annuler" 
                icon="pi pi-times" 
                text 
                onClick={() => setActionDialog(false)} 
            />
            <Button 
                label={
                    actionType === 'payment' ? 'Enregistrer le paiement' :
                    actionType === 'reminder' ? 'Envoyer la relance' :
                    'Programmer l\'échéancier'
                } 
                icon={
                    actionType === 'payment' ? 'pi pi-check-circle' :
                    actionType === 'reminder' ? 'pi pi-send' :
                    'pi pi-calendar'
                } 
                text 
                onClick={handleAction} 
            />
        </>
    );

    const getActionTitle = () => {
        switch (actionType) {
            case 'payment': return 'Enregistrer un paiement';
            case 'reminder': return 'Envoyer une relance';
            case 'schedule': return 'Planifier un échéancier';
            default: return 'Action';
        }
    };

    return (
        <div className="grid">
            <div className="col-12">
                <Card>
                    <Toast ref={toast} />
                    <Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate} />

                    <DataTable
                        ref={dt}
                        value={factures}
                        selection={selectedFactures}
                        onSelectionChange={(e) => setSelectedFactures(e.value)}
                        selectionMode="multiple"
                        dataKey="id"
                        paginator
                        rows={10}
                        rowsPerPageOptions={[5, 10, 25]}
                        className="datatable-responsive"
                        paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                        currentPageReportTemplate="Affichage de {first} à {last} sur {totalRecords} factures"
                        globalFilter={globalFilter}
                        emptyMessage="Aucune facture impayée trouvée."
                        header={header}
                        responsiveLayout="scroll"
                        loading={loading}
                        sortField="dateEcheance"
                        sortOrder={1}
                    >
                        <Column selectionMode="multiple" headerStyle={{ width: '4rem' }} />
                        <Column field="numero" header="Numéro" sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="objet" header="Objet" sortable headerStyle={{ minWidth: '15rem' }} />
                        <Column field="client" header="Client" body={clientBodyTemplate} sortable headerStyle={{ minWidth: '12rem' }} />
                        <Column field="dateEmission" header="Date émission" body={(rowData) => formatDate(rowData.dateEmission)} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="dateEcheance" header="Date échéance" body={dueDateBodyTemplate} sortable headerStyle={{ minWidth: '12rem' }} />
                        <Column field="montantTTC" header="Montant dû" body={amountBodyTemplate} sortable headerStyle={{ minWidth: '12rem' }} />
                        <Column field="statut" header="Statut" body={statusBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
                        <Column body={actionBodyTemplate} headerStyle={{ minWidth: '15rem' }} />
                    </DataTable>

                    <Dialog 
                        visible={actionDialog} 
                        style={{ width: '600px' }} 
                        header={getActionTitle()}
                        modal 
                        className="p-fluid" 
                        footer={actionDialogFooter} 
                        onHide={() => setActionDialog(false)}
                    >
                        <div className="formgrid grid">
                            <div className="field col-12">
                                <p>
                                    Facture: <strong>{selectedFacture?.numero} - {selectedFacture?.objet}</strong>
                                </p>
                                <p>
                                    Client: <strong>{selectedFacture?.client ? `${selectedFacture.client.prenom} ${selectedFacture.client.nom}` : 'N/A'}</strong>
                                </p>
                                <p>
                                    Montant dû: <strong>{selectedFacture ? formatCurrency(selectedFacture.montantTTC || 0) : ''}</strong>
                                </p>
                                {selectedFacture && (
                                    <p>
                                        Retard: <strong>{getDaysOverdue(selectedFacture.dateEcheance)} jour(s)</strong>
                                    </p>
                                )}
                            </div>

                            {actionType === 'payment' && (
                                <>
                                    <div className="field col-12 md:col-6">
                                        <label htmlFor="datePaiement">Date de paiement</label>
                                        <Calendar
                                            id="datePaiement"
                                            value={paymentData.datePaiement}
                                            onChange={(e) => setPaymentData(prev => ({ ...prev, datePaiement: e.value || new Date() }))}
                                            dateFormat="dd/mm/yy"
                                            showIcon
                                        />
                                    </div>

                                    <div className="field col-12 md:col-6">
                                        <label htmlFor="montantPaye">Montant payé (€)</label>
                                        <InputText 
                                            id="montantPaye" 
                                            type="number"
                                            value={paymentData.montantPaye.toString()} 
                                            onChange={(e) => setPaymentData(prev => ({ ...prev, montantPaye: parseFloat(e.target.value) || 0 }))} 
                                        />
                                    </div>

                                    <div className="field col-12">
                                        <label htmlFor="modePaiement">Mode de paiement</label>
                                        <Dropdown 
                                            id="modePaiement" 
                                            value={paymentData.modePaiement} 
                                            options={paymentMethods} 
                                            onChange={(e) => setPaymentData(prev => ({ ...prev, modePaiement: e.value }))} 
                                            placeholder="Sélectionnez un mode de paiement"
                                        />
                                    </div>

                                    <div className="field col-12">
                                        <label htmlFor="paymentNotes">Notes de paiement</label>
                                        <InputTextarea 
                                            id="paymentNotes" 
                                            value={paymentData.notes} 
                                            onChange={(e) => setPaymentData(prev => ({ ...prev, notes: e.target.value }))} 
                                            rows={3} 
                                            placeholder="Notes sur le paiement..."
                                        />
                                    </div>
                                </>
                            )}

                            {actionType === 'reminder' && (
                                <>
                                    <div className="field col-12">
                                        <label htmlFor="reminderType">Type de relance</label>
                                        <Dropdown 
                                            id="reminderType" 
                                            value={reminderData.type} 
                                            options={reminderTypes} 
                                            onChange={(e) => setReminderData(prev => ({ ...prev, type: e.value }))} 
                                            placeholder="Sélectionnez le type de relance"
                                        />
                                    </div>

                                    <div className="field col-12">
                                        <label htmlFor="reminderMessage">Message de relance</label>
                                        <InputTextarea 
                                            id="reminderMessage" 
                                            value={reminderData.message} 
                                            onChange={(e) => setReminderData(prev => ({ ...prev, message: e.target.value }))} 
                                            rows={5} 
                                            placeholder="Message à envoyer au client..."
                                        />
                                    </div>
                                </>
                            )}

                            {actionType === 'schedule' && (
                                <div className="field col-12">
                                    <p>
                                        <i className="pi pi-info-circle mr-2"></i>
                                        Un échéancier de paiement sera proposé au client pour faciliter le règlement de cette facture.
                                    </p>
                                    <p>
                                        Fonctionnalités prévues :
                                    </p>
                                    <ul>
                                        <li>Division du montant en plusieurs échéances</li>
                                        <li>Définition des dates de paiement</li>
                                        <li>Envoi automatique de rappels</li>
                                        <li>Suivi des paiements partiels</li>
                                    </ul>
                                </div>
                            )}
                        </div>
                    </Dialog>
                </Card>
            </div>
        </div>
    );
};

export default FacturesImpayeesPage;

