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


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 { Dropdown } from 'primereact/dropdown';
import { InputTextarea } from 'primereact/inputtextarea';
import { ProgressBar } from 'primereact/progressbar';
import { devisService } from '../../../../services/api';
import { formatDate, formatCurrency } from '../../../../utils/formatters';
import type { Devis } from '../../../../types/btp';
import { StatutDevis } from '../../../../types/btp';

const DevisAttentePage = () => {
    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<'accept' | 'refuse' | 'send' | 'extend'>('send');
    const [actionNotes, setActionNotes] = 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 en attente (brouillon ou envoyé)
            const devisEnAttente = data.filter(devis => 
                devis.statut === 'BROUILLON' || devis.statut === 'ENVOYE'
            );
            setDevis(devisEnAttente);
        } catch (error) {
            console.error('Erreur lors du chargement des devis:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger les devis en attente',
                life: 3000
            });
        } finally {
            setLoading(false);
        }
    };

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

    const isExpiringSoon = (dateValidite: string | Date) => {
        const days = getDaysUntilExpiry(dateValidite);
        return days >= 0 && days <= 7; // Expire dans les 7 prochains jours
    };

    const isExpired = (dateValidite: string | Date) => {
        const days = getDaysUntilExpiry(dateValidite);
        return days < 0;
    };

    const getUrgencyLevel = (dateValidite: string | Date) => {
        const days = getDaysUntilExpiry(dateValidite);
        if (days < 0) return { level: 'EXPIRÉ', color: 'red', severity: 'danger' as const };
        if (days <= 3) return { level: 'URGENT', color: 'red', severity: 'danger' as const };
        if (days <= 7) return { level: 'BIENTÔT', color: 'orange', severity: 'warning' as const };
        return { level: 'NORMAL', color: 'green', severity: 'success' as const };
    };

    const sendDevis = (devisItem: Devis) => {
        setSelectedDevisItem(devisItem);
        setActionType('send');
        setActionNotes('');
        setActionDialog(true);
    };

    const acceptDevis = (devisItem: Devis) => {
        setSelectedDevisItem(devisItem);
        setActionType('accept');
        setActionNotes('');
        setActionDialog(true);
    };

    const refuseDevis = (devisItem: Devis) => {
        setSelectedDevisItem(devisItem);
        setActionType('refuse');
        setActionNotes('');
        setActionDialog(true);
    };

    const extendValidité = (devisItem: Devis) => {
        setSelectedDevisItem(devisItem);
        setActionType('extend');
        setActionNotes('');
        setActionDialog(true);
    };

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

        try {
            let newStatut = selectedDevisItem.statut;
            let message = '';

            switch (actionType) {
                case 'send':
                    newStatut = StatutDevis.ENVOYE;
                    message = 'Devis envoyé au client';
                    break;
                case 'accept':
                    newStatut = StatutDevis.ACCEPTE;
                    message = 'Devis accepté par le client';
                    break;
                case 'refuse':
                    newStatut = StatutDevis.REFUSE;
                    message = 'Devis refusé par le client';
                    break;
                case 'extend':
                    // Prolonger la validité de 30 jours
                    const newValidityDate = new Date(selectedDevisItem.dateValidite);
                    newValidityDate.setDate(newValidityDate.getDate() + 30);
                    // Pour cette démo, on simule juste le message
                    message = 'Validité du devis prolongée de 30 jours';
                    break;
            }

            // TODO: Implémenter quand l'API backend sera disponible
            console.log(`Action ${actionType} sur devis ${selectedDevisItem.numero}:`, {
                nouveauStatut: newStatut,
                notes: actionNotes
            });

            // Simulation de succès
            if (actionType === 'accept' || actionType === 'refuse') {
                // Retirer le devis de la liste car il n'est plus en attente
                setDevis(prev => prev.filter(d => d.id !== selectedDevisItem.id));
            }

            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 bulkSend = 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'envoi en lot
        console.log('Envoi en lot de', selectedDevis.length, 'devis');
        
        setSelectedDevis([]);
        toast.current?.show({
            severity: 'success',
            summary: 'Succès',
            detail: `${selectedDevis.length} devis envoyé(s) (simulation)`,
            life: 3000
        });
    };

    const generateFollowUpReport = () => {
        const urgent = devis.filter(d => getUrgencyLevel(d.dateValidite).level === 'URGENT');
        const expiringSoon = devis.filter(d => getUrgencyLevel(d.dateValidite).level === 'BIENTÔT');
        const expired = devis.filter(d => getUrgencyLevel(d.dateValidite).level === 'EXPIRÉ');
        
        const report = `
=== RAPPORT DE SUIVI DEVIS EN ATTENTE ===
Date du rapport: ${new Date().toLocaleDateString('fr-FR')}

DEVIS URGENTS (${urgent.length}):
${urgent.map(d => `
- ${d.numero} - ${d.objet}
  Client: ${d.client ? `${d.client.prenom} ${d.client.nom}` : 'N/A'}
  Montant: ${formatCurrency(d.montantTTC || 0)}
  Expire: ${formatDate(d.dateValidite)}
`).join('')}

DEVIS EXPIRANT BIENTÔT (${expiringSoon.length}):
${expiringSoon.map(d => `
- ${d.numero} - ${d.objet}
  Client: ${d.client ? `${d.client.prenom} ${d.client.nom}` : 'N/A'}
  Montant: ${formatCurrency(d.montantTTC || 0)}
  Expire: ${formatDate(d.dateValidite)}
`).join('')}

DEVIS EXPIRÉS (${expired.length}):
${expired.map(d => `
- ${d.numero} - ${d.objet}
  Client: ${d.client ? `${d.client.prenom} ${d.client.nom}` : 'N/A'}
  Montant: ${formatCurrency(d.montantTTC || 0)}
  Expiré: ${formatDate(d.dateValidite)}
`).join('')}

STATISTIQUES:
- Total devis en attente: ${devis.length}
- Montant total en attente: ${formatCurrency(devis.reduce((sum, d) => sum + (d.montantTTC || 0), 0))}
- Taux d'urgence: ${Math.round(((urgent.length + expiringSoon.length) / devis.length) * 100)}%
        `;
        
        const blob = new Blob([report], { type: 'text/plain;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `suivi_devis_attente_${new Date().toISOString().split('T')[0]}.txt`;
        link.click();
        
        toast.current?.show({
            severity: 'success',
            summary: 'Rapport généré',
            detail: 'Le rapport de suivi a été téléchargé',
            life: 3000
        });
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="my-2 flex gap-2">
                <h5 className="m-0 flex align-items-center">
                    <i className="pi pi-clock mr-2 text-orange-500"></i>
                    Devis en attente ({devis.length})
                </h5>
                <Button 
                    label="Envoyer sélection" 
                    icon="pi pi-send" 
                    severity="info" 
                    size="small"
                    onClick={bulkSend}
                    disabled={selectedDevis.length === 0}
                />
                <Button 
                    label="Rapport de suivi" 
                    icon="pi pi-file-export" 
                    severity="help" 
                    size="small"
                    onClick={generateFollowUpReport}
                />
            </div>
        );
    };

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

    const actionBodyTemplate = (rowData: Devis) => {
        const expired = isExpired(rowData.dateValidite);
        
        return (
            <div className="flex gap-1">
                {rowData.statut === 'BROUILLON' && (
                    <Button 
                        icon="pi pi-send" 
                        rounded 
                        severity="info" 
                        size="small"
                        tooltip="Envoyer au client"
                        onClick={() => sendDevis(rowData)}
                    />
                )}
                {rowData.statut === 'ENVOYE' && !expired && (
                    <>
                        <Button 
                            icon="pi pi-check" 
                            rounded 
                            severity="success" 
                            size="small"
                            tooltip="Marquer comme accepté"
                            onClick={() => acceptDevis(rowData)}
                        />
                        <Button 
                            icon="pi pi-times" 
                            rounded 
                            severity="danger" 
                            size="small"
                            tooltip="Marquer comme refusé"
                            onClick={() => refuseDevis(rowData)}
                        />
                    </>
                )}
                <Button 
                    icon="pi pi-calendar-plus" 
                    rounded 
                    severity="warning" 
                    size="small"
                    tooltip="Prolonger la validité"
                    onClick={() => extendValidité(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 urgency = getUrgencyLevel(rowData.dateValidite);
        
        return (
            <div className="flex align-items-center gap-2">
                <Tag
                    value={rowData.statut === 'BROUILLON' ? 'Brouillon' : 'Envoyé'}
                    severity={(rowData.statut === 'BROUILLON' ? 'secondary' : 'info') as any}
                />
                <Tag 
                    value={urgency.level} 
                    severity={urgency.severity}
                />
            </div>
        );
    };

    const validityBodyTemplate = (rowData: Devis) => {
        const days = getDaysUntilExpiry(rowData.dateValidite);
        const urgency = getUrgencyLevel(rowData.dateValidite);
        
        return (
            <div className={urgency.level === 'EXPIRÉ' ? 'text-red-500 font-bold' : ''}>
                <div>{formatDate(rowData.dateValidite)}</div>
                <small className={`text-${urgency.color}-500`}>
                    {days < 0 ? `Expiré il y a ${Math.abs(days)} jour${Math.abs(days) > 1 ? 's' : ''}` : 
                     days === 0 ? 'Expire aujourd\'hui' :
                     `Expire dans ${days} jour${days > 1 ? 's' : ''}`}
                </small>
            </div>
        );
    };

    const progressBodyTemplate = (rowData: Devis) => {
        const totalDays = Math.ceil((new Date(rowData.dateValidite).getTime() - new Date(rowData.dateEmission).getTime()) / (1000 * 60 * 60 * 24));
        const remainingDays = getDaysUntilExpiry(rowData.dateValidite);
        const elapsed = Math.max(0, totalDays - remainingDays);
        const progress = Math.min((elapsed / totalDays) * 100, 100);
        
        const urgency = getUrgencyLevel(rowData.dateValidite);
        let color = '#22c55e'; // green
        if (urgency.level === 'BIENTÔT') color = '#f59e0b'; // orange
        if (urgency.level === 'URGENT' || urgency.level === 'EXPIRÉ') color = '#ef4444'; // red
        
        return (
            <div className="flex align-items-center gap-2">
                <ProgressBar 
                    value={progress} 
                    style={{ height: '6px', width: '100px' }}
                    color={color}
                />
                <span className="text-sm">
                    {Math.round(progress)}%
                </span>
            </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 en attente de réponse client</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 === 'send' ? 'Envoyer' :
                    actionType === 'accept' ? 'Accepter' :
                    actionType === 'refuse' ? 'Refuser' :
                    'Prolonger'
                } 
                icon={
                    actionType === 'send' ? 'pi pi-send' :
                    actionType === 'accept' ? 'pi pi-check' :
                    actionType === 'refuse' ? 'pi pi-times' :
                    'pi pi-calendar-plus'
                } 
                text 
                onClick={handleAction} 
            />
        </>
    );

    const getActionTitle = () => {
        switch (actionType) {
            case 'send': return 'Envoyer le devis';
            case 'accept': return 'Accepter le devis';
            case 'refuse': return 'Refuser le devis';
            case 'extend': return 'Prolonger la validité';
            default: return 'Action';
        }
    };

    const getActionDescription = () => {
        switch (actionType) {
            case 'send': return 'Confirmer l\'envoi de ce devis au client ?';
            case 'accept': return 'Marquer ce devis comme accepté par le client ?';
            case 'refuse': return 'Marquer ce devis comme refusé par le client ?';
            case 'extend': return 'Prolonger la validité de ce devis de 30 jours ?';
            default: return '';
        }
    };

    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 en attente 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="dateEmission" header="Date émission" body={(rowData) => formatDate(rowData.dateEmission)} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="dateValidite" header="Date validité" body={validityBodyTemplate} sortable headerStyle={{ minWidth: '12rem' }} />
                        <Column field="progress" header="Progression" body={progressBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
                        <Column field="montantTTC" header="Montant TTC" body={(rowData) => formatCurrency(rowData.montantTTC)} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="statut" header="Statut/Urgence" body={statusBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
                        <Column body={actionBodyTemplate} headerStyle={{ minWidth: '15rem' }} />
                    </DataTable>

                    <Dialog 
                        visible={actionDialog} 
                        style={{ width: '500px' }} 
                        header={getActionTitle()}
                        modal 
                        className="p-fluid" 
                        footer={actionDialogFooter} 
                        onHide={() => setActionDialog(false)}
                    >
                        <div className="formgrid grid">
                            <div className="field col-12">
                                <p>{getActionDescription()}</p>
                                <p>
                                    Devis: <strong>{selectedDevisItem?.numero} - {selectedDevisItem?.objet}</strong>
                                </p>
                                <p>
                                    Montant: <strong>{selectedDevisItem ? formatCurrency(selectedDevisItem.montantTTC || 0) : ''}</strong>
                                </p>
                            </div>

                            <div className="field col-12">
                                <label htmlFor="actionNotes">Notes (optionnel)</label>
                                <InputTextarea 
                                    id="actionNotes" 
                                    value={actionNotes} 
                                    onChange={(e) => setActionNotes(e.target.value)} 
                                    rows={3} 
                                    placeholder="Ajoutez des notes sur cette action..."
                                />
                            </div>
                        </div>
                    </Dialog>
                </Card>
            </div>
        </div>
    );
};

export default DevisAttentePage;

