'use client';

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

const DevisDetailPage = () => {
    const params = useParams();
    const router = useRouter();
    const toast = useRef<Toast>(null);
    const menuRef = useRef<Menu>(null);
    
    const [devis, setDevis] = useState<Devis | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const devisId = params.id as string;

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

    const loadDevis = async () => {
        try {
            setLoading(true);
            const response = await devisService.getById(devisId);
            setDevis(response.data);
        } catch (error) {
            console.error('Erreur lors du chargement du devis:', error);
            setError('Impossible de charger le devis');
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger le devis'
            });
        } finally {
            setLoading(false);
        }
    };

    const getStatutSeverity = (statut: string) => {
        switch (statut) {
            case 'ACCEPTE': return 'success';
            case 'REFUSE': return 'danger';
            case 'EXPIRE': return 'warning';
            case 'EN_ATTENTE': return 'info';
            case 'BROUILLON': return 'secondary';
            default: return 'info';
        }
    };

    const menuItems = [
        {
            label: 'Modifier',
            icon: 'pi pi-pencil',
            command: () => router.push(`/devis/${devisId}/edit`)
        },
        {
            label: 'Dupliquer',
            icon: 'pi pi-copy',
            command: () => router.push(`/devis/${devisId}/duplicate`)
        },
        {
            label: 'Convertir en facture',
            icon: 'pi pi-arrow-right',
            command: () => router.push(`/devis/${devisId}/convert`)
        },
        {
            separator: true
        },
        {
            label: 'Imprimer',
            icon: 'pi pi-print',
            command: () => window.print()
        },
        {
            label: 'Télécharger PDF',
            icon: 'pi pi-download',
            command: () => handleDownloadPDF()
        },
        {
            separator: true
        },
        {
            label: 'Supprimer',
            icon: 'pi pi-trash',
            className: 'text-red-500',
            command: () => handleDelete()
        }
    ];

    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 handleDelete = async () => {
        try {
            await devisService.delete(devisId);
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Devis supprimé avec succès'
            });
            router.push('/devis');
        } catch (error) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors de la suppression'
            });
        }
    };

    const handleAccept = async () => {
        try {
            await devisService.updateStatut(devisId, 'ACCEPTE');
            loadDevis();
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Devis accepté'
            });
        } catch (error) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors de l\'acceptation'
            });
        }
    };

    const handleReject = async () => {
        try {
            await devisService.updateStatut(devisId, 'REFUSE');
            loadDevis();
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Devis refusé'
            });
        } catch (error) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors du refus'
            });
        }
    };

    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('/devis')}
            />
        </div>
    );

    const toolbarEndTemplate = () => (
        <div className="flex align-items-center gap-2">
            {devis?.statut === 'EN_ATTENTE' && (
                <>
                    <Button
                        label="Accepter"
                        icon="pi pi-check"
                        className="p-button-success"
                        onClick={handleAccept}
                    />
                    <Button
                        label="Refuser"
                        icon="pi pi-times"
                        className="p-button-danger p-button-outlined"
                        onClick={handleReject}
                    />
                </>
            )}
            <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 || !devis) {
        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>Devis introuvable</h3>
                    <p className="text-600 mb-4">{error || 'Le devis demandé n\'existe pas'}</p>
                    <Button
                        label="Retour à la liste"
                        icon="pi pi-arrow-left"
                        onClick={() => router.push('/devis')}
                    />
                </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 du devis */}
            <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">Devis #{devis.numero}</h2>
                            <p className="text-600 mb-3">{devis.objet}</p>
                            <Tag 
                                value={devis.statut} 
                                severity={getStatutSeverity(devis.statut)}
                                className="mb-2"
                            />
                        </div>
                        <div className="text-right">
                            <div className="text-3xl font-bold text-primary mb-2">
                                {formatCurrency(devis.montantTTC)}
                            </div>
                            <div className="text-sm text-600">
                                HT: {formatCurrency(devis.montantHT)}
                            </div>
                        </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(devis.dateEmission)}</p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">Date de validité:</label>
                                <p>{formatDate(devis.dateValidite)}</p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">Client:</label>
                                <p>{typeof devis.client === 'string' ? devis.client : devis.client?.nom}</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(devis.montantHT)}</p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">TVA ({devis.tauxTVA}%):</label>
                                <p>{formatCurrency(devis.montantTTC - devis.montantHT)}</p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">Montant TTC:</label>
                                <p className="text-xl font-bold text-primary">{formatCurrency(devis.montantTTC)}</p>
                            </div>
                        </div>
                    </div>

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

            {/* Lignes du devis */}
            {devis.lignes && devis.lignes.length > 0 && (
                <div className="col-12">
                    <Card title="Détail des prestations">
                        <DataTable value={devis.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 */}
            <div className="col-12">
                <Card title="Historique">
                    <Timeline 
                        value={[
                            {
                                status: 'Créé',
                                date: devis.dateEmission,
                                icon: 'pi pi-plus',
                                color: '#9C27B0'
                            },
                            ...(devis.statut === 'ACCEPTE' ? [{
                                status: 'Accepté',
                                date: new Date(),
                                icon: 'pi pi-check',
                                color: '#4CAF50'
                            }] : []),
                            ...(devis.statut === 'REFUSE' ? [{
                                status: 'Refusé',
                                date: new Date(),
                                icon: 'pi pi-times',
                                color: '#F44336'
                            }] : [])
                        ]}
                        opposite={(item) => formatDate(item.date)}
                        content={(item) => (
                            <div className="flex align-items-center">
                                <Badge value={item.status} style={{ backgroundColor: item.color }} />
                            </div>
                        )}
                    />
                </Card>
            </div>
        </div>
    );
};

export default DevisDetailPage;
