'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 { InputNumber } from 'primereact/inputnumber';
import { Chip } from 'primereact/chip';
import { devisService } from '../../../../services/api';
import { formatDate, formatCurrency } from '../../../../utils/formatters';
import type { Devis } from '../../../../types/btp';
import devisActionsService from '../../../../services/devisActionsService';

const DevisExpiresPage = () => {
    const [devis, setDevis] = useState<Devis[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [selectedDevis, setSelectedDevis] = useState<Devis[]>([]);
    const [actionDialog, setActionDialog] = useState(false);
    const [selectedDevisItem, setSelectedDevisItem] = useState<Devis | null>(null);
    const [actionType, setActionType] = useState<'renew' | 'archive' | 'follow_up'>('renew');
    const [renewData, setRenewData] = useState({
        newValidityDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        adjustments: '',
        newPrice: 0
    });
    const [followUpNotes, setFollowUpNotes] = useState('');
    const toast = useRef<Toast>(null);
    const dt = useRef<DataTable<Devis[]>>(null);

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

    const loadDevis = async () => {
        try {
            setLoading(true);
            const data = await devisService.getAll();
            // Filtrer les devis expirés ou marqués comme expirés
            const devisExpires = data.filter(devis => {
                const today = new Date();
                const validityDate = new Date(devis.dateValidite);
                return devis.statut === 'EXPIRE' || (devis.statut === 'ENVOYE' && validityDate < today);
            });
            setDevis(devisExpires);
        } catch (error) {
            console.error('Erreur lors du chargement des devis:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger les devis expirés',
                life: 3000
            });
        } finally {
            setLoading(false);
        }
    };

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

    const getExpiryCategory = (dateValidite: string | Date) => {
        const days = getDaysExpired(dateValidite);
        if (days <= 7) return { category: 'RÉCEMMENT', color: 'orange', severity: 'warning' as const };
        if (days <= 30) return { category: 'ANCIEN', color: 'red', severity: 'danger' as const };
        return { category: 'TRÈS ANCIEN', color: 'darkred', severity: 'danger' as const };
    };

    const calculateLostValue = () => {
        return devis.reduce((sum, d) => sum + (d.montantTTC || 0), 0);
    };

    const renewDevis = (devisItem: Devis) => {
        setSelectedDevisItem(devisItem);
        setActionType('renew');
        setRenewData({
            newValidityDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
            adjustments: '',
            newPrice: devisItem.montantTTC || 0
        });
        setActionDialog(true);
    };

    const archiveDevis = (devisItem: Devis) => {
        setSelectedDevisItem(devisItem);
        setActionType('archive');
        setActionDialog(true);
    };

    const followUpDevis = (devisItem: Devis) => {
        setSelectedDevisItem(devisItem);
        setActionType('follow_up');
        setFollowUpNotes('');
        setActionDialog(true);
    };

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

        try {
            let message = '';

            switch (actionType) {
                case 'renew':
                    await devisActionsService.renewDevis({
                        devisId: selectedDevisItem.id,
                        nouveaueDateValidite: renewData.newValidityDate.toISOString()
                    });
                    message = 'Devis renouvelé avec succès';
                    break;
                    
                case 'archive':
                    await devisActionsService.archiveDevis({
                        devisId: selectedDevisItem.id,
                        motif: followUpNotes
                    });
                    setDevis(prev => prev.filter(d => d.id !== selectedDevisItem.id));
                    message = 'Devis archivé avec succès';
                    break;
                    
                case 'follow_up':
                    await devisActionsService.followUpClient({
                        devisId: selectedDevisItem.id,
                        clientId: selectedDevisItem.client.id,
                        type: 'email',
                        message: followUpNotes
                    });
                    message = 'Suivi client effectué avec succès';
                    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 bulkArchive = async () => {
        if (selectedDevis.length === 0) {
            toast.current?.show({
                severity: 'warn',
                summary: 'Attention',
                detail: 'Veuillez sélectionner au moins un devis',
                life: 3000
            });
            return;
        }

        // Simulation d'archivage en lot
        console.log('Archivage en lot de', selectedDevis.length, 'devis');
        
        setDevis(prev => prev.filter(d => !selectedDevis.includes(d)));
        setSelectedDevis([]);
        
        toast.current?.show({
            severity: 'success',
            summary: 'Succès',
            detail: `${selectedDevis.length} devis archivé(s) (simulation)`,
            life: 3000
        });
    };

    const generateLossAnalysis = () => {
        const totalLoss = calculateLostValue();
        const recentlyExpired = devis.filter(d => getDaysExpired(d.dateValidite) <= 7);
        const oldExpired = devis.filter(d => getDaysExpired(d.dateValidite) > 30);
        
        const report = `
=== ANALYSE DES DEVIS EXPIRÉS ===
Date du rapport: ${new Date().toLocaleDateString('fr-FR')}

STATISTIQUES GÉNÉRALES:
- Nombre total de devis expirés: ${devis.length}
- Valeur totale perdue: ${formatCurrency(totalLoss)}
- Valeur moyenne par devis: ${formatCurrency(totalLoss / (devis.length || 1))}

RÉPARTITION PAR ANCIENNETÉ:
- Récemment expirés (≤7 jours): ${recentlyExpired.length} devis, ${formatCurrency(recentlyExpired.reduce((sum, d) => sum + (d.montantTTC || 0), 0))}
- Anciens (>30 jours): ${oldExpired.length} devis, ${formatCurrency(oldExpired.reduce((sum, d) => sum + (d.montantTTC || 0), 0))}

DEVIS À FORT POTENTIEL (>5000€):
${devis.filter(d => (d.montantTTC || 0) > 5000).map(d => `
- ${d.numero} - ${d.objet}
  Client: ${d.client ? `${d.client.prenom} ${d.client.nom}` : 'N/A'}
  Montant: ${formatCurrency(d.montantTTC || 0)}
  Expiré depuis: ${getDaysExpired(d.dateValidite)} jours
`).join('')}

ANALYSE PAR CLIENT:
${getClientAnalysis()}

RECOMMANDATIONS:
- Relancer les clients pour les devis récemment expirés
- Proposer des devis renouvelés avec ajustements
- Analyser les causes d'expiration pour améliorer le taux de conversion
- Archiver les devis très anciens après relance finale
        `;
        
        const blob = new Blob([report], { type: 'text/plain;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `analyse_devis_expires_${new Date().toISOString().split('T')[0]}.txt`;
        link.click();
        
        toast.current?.show({
            severity: 'success',
            summary: 'Analyse générée',
            detail: 'Le rapport d\'analyse a été téléchargé',
            life: 3000
        });
    };

    const getClientAnalysis = () => {
        const clientStats = {};
        devis.forEach(d => {
            if (d.client) {
                const clientKey = `${d.client.prenom} ${d.client.nom}`;
                if (!clientStats[clientKey]) {
                    clientStats[clientKey] = { count: 0, value: 0 };
                }
                clientStats[clientKey].count++;
                clientStats[clientKey].value += d.montantTTC || 0;
            }
        });
        
        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} devis, ${formatCurrency(data.value)}`)
            .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-times-circle mr-2"></i>
                    Devis expirés ({devis.length})
                </h5>
                <Chip 
                    label={`Valeur perdue: ${formatCurrency(calculateLostValue())}`} 
                    className="bg-red-100 text-red-800"
                />
                <Button 
                    label="Archiver sélection" 
                    icon="pi pi-archive" 
                    severity={"secondary" as any} 
                    size="small"
                    onClick={bulkArchive}
                    disabled={selectedDevis.length === 0}
                />
                <Button 
                    label="Analyse des pertes" 
                    icon="pi pi-chart-line" 
                    severity="danger" 
                    size="small"
                    onClick={generateLossAnalysis}
                />
            </div>
        );
    };

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

    const actionBodyTemplate = (rowData: Devis) => {
        const category = getExpiryCategory(rowData.dateValidite);
        const isRecent = category.category === 'RÉCEMMENT';
        
        return (
            <div className="flex gap-1">
                {isRecent && (
                    <Button 
                        icon="pi pi-refresh" 
                        rounded 
                        severity="warning" 
                        size="small"
                        tooltip="Renouveler le devis"
                        onClick={() => renewDevis(rowData)}
                    />
                )}
                <Button 
                    icon="pi pi-phone" 
                    rounded 
                    severity="info" 
                    size="small"
                    tooltip="Suivi client"
                    onClick={() => followUpDevis(rowData)}
                />
                <Button 
                    icon="pi pi-archive" 
                    rounded 
                    severity={"secondary" as any} 
                    size="small"
                    tooltip="Archiver"
                    onClick={() => archiveDevis(rowData)}
                />
                <Button 
                    icon="pi pi-eye" 
                    rounded 
                    severity="help" 
                    size="small"
                    tooltip="Voir détails"
                    onClick={() => {
                        toast.current?.show({
                            severity: 'info',
                            summary: 'Info',
                            detail: `Détails du devis ${rowData.numero}`,
                            life: 3000
                        });
                    }}
                />
            </div>
        );
    };

    const statusBodyTemplate = (rowData: Devis) => {
        const category = getExpiryCategory(rowData.dateValidite);
        
        return (
            <div className="flex align-items-center gap-2">
                <Tag value="Expiré" severity="danger" />
                <Tag 
                    value={category.category} 
                    severity={category.severity}
                />
            </div>
        );
    };

    const expiryBodyTemplate = (rowData: Devis) => {
        const days = getDaysExpired(rowData.dateValidite);
        const category = getExpiryCategory(rowData.dateValidite);
        
        return (
            <div className="text-red-600">
                <div className="font-bold">{formatDate(rowData.dateValidite)}</div>
                <small>
                    {days === 0 ? 'Expire aujourd\'hui' : 
                     days === 1 ? 'Expiré hier' :
                     `Expiré il y a ${days} jours`}
                </small>
                <div className="mt-1">
                    <Chip 
                        label={category.category} 
                        style={{ backgroundColor: category.color, color: 'white', fontSize: '0.7rem' }}
                    />
                </div>
            </div>
        );
    };

    const potentialBodyTemplate = (rowData: Devis) => {
        const amount = rowData.montantTTC || 0;
        let severity = 'secondary';
        let label = 'Faible';
        
        if (amount > 10000) {
            severity = 'danger';
            label = 'Très élevé';
        } else if (amount > 5000) {
            severity = 'warning';
            label = 'Élevé';
        } else if (amount > 1000) {
            severity = 'info';
            label = 'Moyen';
        }
        
        return (
            <div>
                <div>{formatCurrency(amount)}</div>
                <Tag value={label} severity={severity as any} className="text-xs mt-1" />
            </div>
        );
    };

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

    const header = (
        <div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
            <h5 className="m-0">Devis expirés - Opportunités perdues</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 === 'renew' ? 'Renouveler' :
                    actionType === 'archive' ? 'Archiver' :
                    'Enregistrer le suivi'
                } 
                icon={
                    actionType === 'renew' ? 'pi pi-refresh' :
                    actionType === 'archive' ? 'pi pi-archive' :
                    'pi pi-check'
                } 
                text 
                onClick={handleAction} 
            />
        </>
    );

    const getActionTitle = () => {
        switch (actionType) {
            case 'renew': return 'Renouveler le devis';
            case 'archive': return 'Archiver le devis';
            case 'follow_up': return 'Suivi client';
            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={devis}
                        selection={selectedDevis}
                        onSelectionChange={(e) => setSelectedDevis(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} devis"
                        globalFilter={globalFilter}
                        emptyMessage="Aucun devis expiré trouvé."
                        header={header}
                        responsiveLayout="scroll"
                        loading={loading}
                        sortField="dateValidite"
                        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="dateValidite" header="Date d'expiration" body={expiryBodyTemplate} sortable headerStyle={{ minWidth: '12rem' }} />
                        <Column field="montantTTC" header="Potentiel perdu" body={potentialBodyTemplate} 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>
                                    Devis: <strong>{selectedDevisItem?.numero} - {selectedDevisItem?.objet}</strong>
                                </p>
                                <p>
                                    Client: <strong>{selectedDevisItem?.client ? `${selectedDevisItem.client.prenom} ${selectedDevisItem.client.nom}` : 'N/A'}</strong>
                                </p>
                                <p>
                                    Montant: <strong>{selectedDevisItem ? formatCurrency(selectedDevisItem.montantTTC || 0) : ''}</strong>
                                </p>
                                <p>
                                    Expiré depuis: <strong>{selectedDevisItem ? getDaysExpired(selectedDevisItem.dateValidite) : 0} jour(s)</strong>
                                </p>
                            </div>

                            {actionType === 'renew' && (
                                <>
                                    <div className="field col-12 md:col-6">
                                        <label htmlFor="newValidityDate">Nouvelle date de validité</label>
                                        <Calendar 
                                            id="newValidityDate" 
                                            value={renewData.newValidityDate} 
                                            onChange={(e) => setRenewData(prev => ({ ...prev, newValidityDate: e.value || new Date() }))} 
                                            dateFormat="dd/mm/yy" 
                                            showIcon 
                                            minDate={new Date()}
                                        />
                                    </div>

                                    <div className="field col-12 md:col-6">
                                        <label htmlFor="newPrice">Nouveau montant (€)</label>
                                        <InputNumber 
                                            id="newPrice" 
                                            value={renewData.newPrice} 
                                            onValueChange={(e) => setRenewData(prev => ({ ...prev, newPrice: e.value || 0 }))} 
                                            mode="currency" 
                                            currency="EUR" 
                                            locale="fr-FR" 
                                        />
                                    </div>

                                    <div className="field col-12">
                                        <label htmlFor="adjustments">Ajustements apportés</label>
                                        <InputTextarea 
                                            id="adjustments" 
                                            value={renewData.adjustments} 
                                            onChange={(e) => setRenewData(prev => ({ ...prev, adjustments: e.target.value }))} 
                                            rows={3} 
                                            placeholder="Décrivez les modifications apportées au devis..."
                                        />
                                    </div>
                                </>
                            )}

                            {actionType === 'archive' && (
                                <div className="field col-12">
                                    <p className="text-600">
                                        <i className="pi pi-info-circle mr-2"></i>
                                        Ce devis sera définitivement archivé et ne sera plus visible dans les listes actives.
                                        Cette action est irréversible.
                                    </p>
                                    <p>
                                        <strong>Confirmer l'archivage de ce devis ?</strong>
                                    </p>
                                </div>
                            )}

                            {actionType === 'follow_up' && (
                                <div className="field col-12">
                                    <label htmlFor="followUpNotes">Notes de suivi client</label>
                                    <InputTextarea 
                                        id="followUpNotes" 
                                        value={followUpNotes} 
                                        onChange={(e) => setFollowUpNotes(e.target.value)} 
                                        rows={4} 
                                        placeholder="Notez vos actions de suivi : appel téléphonique, email, visite, résultats obtenus..."
                                    />
                                    <small className="text-600">
                                        Ces notes seront ajoutées à l'historique du client pour le suivi commercial.
                                    </small>
                                </div>
                            )}
                        </div>
                    </Dialog>
                </Card>
            </div>
        </div>
    );
};

export default DevisExpiresPage;


