'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 { Dialog } from 'primereact/dialog';
import { Toast } from 'primereact/toast';
import { Toolbar } from 'primereact/toolbar';
import { Tag } from 'primereact/tag';
import { Dropdown } from 'primereact/dropdown';
import { Calendar } from 'primereact/calendar';
import { InputTextarea } from 'primereact/inputtextarea';
import { InputNumber } from 'primereact/inputnumber';
import { devisService, clientService } from '../../../services/api';
import { formatDate, formatCurrency } from '../../../utils/formatters';
import { ErrorHandler } from '../../../services/errorHandler';
import type { Devis } from '../../../types/btp';
import { 
    ActionButtonGroup, 
    ViewButton, 
    EditButton, 
    DeleteButton,
    PrintButton,
    ActionButton
} from '../../../components/ui/ActionButton';

const DevisPage = () => {
    const [devis, setDevis] = useState<Devis[]>([]);
    const [clients, setClients] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [selectedDevis, setSelectedDevis] = useState<Devis[]>([]);
    const [devisDialog, setDevisDialog] = useState(false);
    const [deleteDevisDialog, setDeleteDevisDialog] = useState(false);
    const [deleteDevisssDialog, setDeleteDevisssDialog] = useState(false);
    const [devisItem, setDevisItem] = useState<Partial<Devis>>({
        id: '',
        numero: '',
        dateEmission: new Date().toISOString(),
        dateValidite: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
        objet: '',
        description: '',
        montantHT: 0,
        montantTTC: 0,
        tauxTVA: 20,
        statut: 'BROUILLON' as any,
        actif: true,
        client: undefined,
        chantier: undefined
    });
    const [submitted, setSubmitted] = useState(false);
    const toast = useRef<Toast>(null);
    const dt = useRef<DataTable<Devis[]>>(null);

    const statuts = [
        { label: 'Brouillon', value: 'BROUILLON' },
        { label: 'Envoyé', value: 'ENVOYE' },
        { label: 'Accepté', value: 'ACCEPTE' },
        { label: 'Refusé', value: 'REFUSE' },
        { label: 'Expiré', value: 'EXPIRE' }
    ];

    useEffect(() => {
        // Initialiser le gestionnaire d'erreurs
        ErrorHandler.setToast(toast);
        loadDevis();
        loadClients();
    }, []);

    const loadDevis = async () => {
        try {
            setLoading(true);
            const data = await devisService.getAll();
            setDevis(data);
        } catch (error) {
            ErrorHandler.handleApiError(error, 'chargement des devis');
        } finally {
            setLoading(false);
        }
    };

    const loadClients = async () => {
        try {
            const data = await clientService.getAll();
            setClients(data.map(client => ({
                label: `${client.prenom} ${client.nom}${client.entreprise ? ' - ' + client.entreprise : ''}`,
                value: client.id,
                client: client
            })));
        } catch (error) {
            ErrorHandler.handleApiError(error, 'chargement des clients');
        }
    };

    const openNew = () => {
        setDevisItem({
            id: '',
            numero: '',
            dateEmission: new Date().toISOString(),
            dateValidite: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
            objet: '',
            description: '',
            montantHT: 0,
            montantTTC: 0,
            tauxTVA: 20,
            statut: 'BROUILLON' as any,
            actif: true,
            client: undefined,
            chantier: undefined
        });
        setSubmitted(false);
        setDevisDialog(true);
    };

    const hideDialog = () => {
        setSubmitted(false);
        setDevisDialog(false);
    };

    const hideDeleteDevisDialog = () => {
        setDeleteDevisDialog(false);
    };

    const hideDeleteDevisssDialog = () => {
        setDeleteDevisssDialog(false);
    };

    const saveDevis = async () => {
        setSubmitted(true);

        // Validation complète côté client
        const validationErrors = [];

        if (!devisItem.objet.trim()) {
            validationErrors.push("L'objet du devis est obligatoire");
        }

        if (!devisItem.client) {
            validationErrors.push("Le client est obligatoire");
        }

        if (!devisItem.numero.trim()) {
            validationErrors.push("Le numéro de devis est obligatoire");
        }

        if (devisItem.montantHT <= 0) {
            validationErrors.push("Le montant HT doit être supérieur à 0");
        }

        if (devisItem.tauxTVA < 0 || devisItem.tauxTVA > 100) {
            validationErrors.push("Le taux de TVA doit être entre 0 et 100%");
        }

        if (!devisItem.dateValidite || new Date(devisItem.dateValidite) <= new Date()) {
            validationErrors.push("La date de validité doit être dans le futur");
        }

        if (validationErrors.length > 0) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreurs de validation',
                detail: validationErrors.join(', '),
                life: 5000
            });
            return;
        }

        if (devisItem.objet.trim() && devisItem.client) {
            try {
                let updatedDevis = [...devis];
                const devisToSave = {
                    ...devisItem,
                    montantTTC: (devisItem.montantHT || 0) * (1 + (devisItem.tauxTVA || 0) / 100)
                } as any;

                if (devisItem.id) {
                    // Mise à jour du devis existant
                    const updatedDevis = await devisService.update(devisItem.id, devisToSave);
                    setDevis(devis.map(d => d.id === devisItem.id ? updatedDevis : d));
                    ErrorHandler.showSuccess('Succès', 'Devis mis à jour avec succès');
                } else {
                    // Création d'un nouveau devis
                    const newDevis = await devisService.create(devisToSave);
                    setDevis([...devis, newDevis]);
                    ErrorHandler.showSuccess('Succès', 'Devis créé avec succès');
                }

                setDevisDialog(false);
                setDevisItem({
                    id: '',
                    numero: '',
                    dateEmission: new Date().toISOString(),
                    dateValidite: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
                    objet: '',
                    description: '',
                    montantHT: 0,
                    montantTTC: 0,
                    tauxTVA: 20,
                    statut: 'BROUILLON' as any,
                    actif: true,
                    client: undefined,
                    chantier: undefined
                });
            } catch (error) {
                ErrorHandler.handleApiError(error, 'sauvegarde du devis');
            }
        }
    };

    const editDevis = (devis: Devis) => {
        setDevisItem({
            ...devis,
            client: devis.client || undefined
        });
        setDevisDialog(true);
    };

    const confirmDeleteDevis = (devis: Devis) => {
        setDevisItem(devis);
        setDeleteDevisDialog(true);
    };

    const deleteDevis = async () => {
        try {
            if (devisItem.id) {
                await devisService.delete(devisItem.id);
                setDevis(devis.filter(d => d.id !== devisItem.id));
                toast.current?.show({
                    severity: 'success',
                    summary: 'Succès',
                    detail: 'Devis supprimé avec succès',
                    life: 3000
                });
            }
            setDeleteDevisDialog(false);
        } catch (error) {
            console.error('Erreur lors de la suppression:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de supprimer le devis',
                life: 3000
            });
        }
    };

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

    const onInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, name: string) => {
        const val = (e.target && e.target.value) || '';
        let _devis = { ...devisItem };
        (_devis as any)[name] = val;
        setDevisItem(_devis);
    };

    const onDateChange = (e: any, name: string) => {
        let _devis = { ...devisItem };
        (_devis as any)[name] = e.value;
        setDevisItem(_devis);
    };

    const onNumberChange = (e: any, name: string) => {
        let _devis = { ...devisItem };
        (_devis as any)[name] = e.value;
        setDevisItem(_devis);

        // Recalcul automatique du TTC
        if (name === 'montantHT' || name === 'tauxTVA') {
            const montantHT = name === 'montantHT' ? e.value : _devis.montantHT;
            const tauxTVA = name === 'tauxTVA' ? e.value : _devis.tauxTVA;
            _devis.montantTTC = montantHT * (1 + tauxTVA / 100);
            setDevisItem(_devis);
        }
    };

    const onDropdownChange = (e: any, name: string) => {
        let _devis = { ...devisItem };
        (_devis as any)[name] = e.value;
        setDevisItem(_devis);
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="my-2">
                <Button 
                    label="Nouveau" 
                    icon="pi pi-plus" 
                    severity="success" 
                    className="mr-2" 
                    onClick={openNew} 
                />
                <Button 
                    label="Supprimer" 
                    icon="pi pi-trash" 
                    severity="danger" 
                    onClick={() => setDeleteDevisssDialog(true)} 
                    disabled={!selectedDevis || selectedDevis.length === 0} 
                />
            </div>
        );
    };

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

    const actionBodyTemplate = (rowData: Devis) => {
        return (
            <ActionButtonGroup>
                <ViewButton 
                    tooltip="Aperçu PDF"
                    onClick={() => {
                        toast.current?.show({
                            severity: 'info',
                            summary: 'Aperçu',
                            detail: `Aperçu du devis ${rowData.numero}`,
                            life: 3000
                        });
                    }}
                />
                <EditButton 
                    tooltip="Modifier"
                    onClick={() => editDevis(rowData)} 
                />
                <DeleteButton 
                    tooltip="Supprimer"
                    onClick={() => confirmDeleteDevis(rowData)} 
                />
            </ActionButtonGroup>
        );
    };

    const statusBodyTemplate = (rowData: Devis) => {
        const getSeverity = (status: string) => {
            switch (status) {
                case 'BROUILLON': return 'secondary';
                case 'ENVOYE': return 'info';
                case 'ACCEPTE': return 'success';
                case 'REFUSE': return 'danger';
                case 'EXPIRE': return 'warning';
                default: return 'secondary';
            }
        };

        const getLabel = (status: string) => {
            switch (status) {
                case 'BROUILLON': return 'Brouillon';
                case 'ENVOYE': return 'Envoyé';
                case 'ACCEPTE': return 'Accepté';
                case 'REFUSE': return 'Refusé';
                case 'EXPIRE': return 'Expiré';
                default: return status;
            }
        };

        return (
            <Tag
                value={getLabel(rowData.statut)}
                severity={getSeverity(rowData.statut) as any}
            />
        );
    };

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

    const dateBodyTemplate = (rowData: Devis, field: string) => {
        const date = (rowData as any)[field];
        return date ? formatDate(date) : '';
    };

    const validityBodyTemplate = (rowData: Devis) => {
        const today = new Date();
        const validityDate = new Date(rowData.dateValidite);
        const isExpired = validityDate < today;
        
        return (
            <div className={`flex align-items-center ${isExpired ? 'text-red-500' : ''}`}>
                {isExpired && <i className="pi pi-exclamation-triangle mr-1"></i>}
                {formatDate(rowData.dateValidite)}
            </div>
        );
    };

    const header = (
        <div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
            <h5 className="m-0">Gestion des Devis</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 devisDialogFooter = (
        <>
            <Button label="Annuler" icon="pi pi-times" text onClick={hideDialog} />
            <Button label="Sauvegarder" icon="pi pi-check" text onClick={saveDevis} />
        </>
    );

    const deleteDevisDialogFooter = (
        <>
            <Button label="Non" icon="pi pi-times" text onClick={hideDeleteDevisDialog} />
            <Button label="Oui" icon="pi pi-check" text onClick={deleteDevis} />
        </>
    );

    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 trouvé."
                        header={header}
                        responsiveLayout="scroll"
                        loading={loading}
                    >
                        <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) => dateBodyTemplate(rowData, 'dateEmission')} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="dateValidite" header="Date validité" body={validityBodyTemplate} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="montantHT" header="Montant HT" body={(rowData) => formatCurrency(rowData.montantHT)} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="montantTTC" header="Montant TTC" body={(rowData) => formatCurrency(rowData.montantTTC)} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="statut" header="Statut" body={statusBodyTemplate} sortable headerStyle={{ minWidth: '8rem' }} />
                        <Column body={actionBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
                    </DataTable>

                    <Dialog 
                        visible={devisDialog} 
                        style={{ width: '700px' }} 
                        header="Détails du Devis" 
                        modal 
                        className="p-fluid" 
                        footer={devisDialogFooter} 
                        onHide={hideDialog}
                    >
                        <div className="formgrid grid">
                            <div className="field col-12 md:col-6">
                                <label htmlFor="numero">Numéro</label>
                                <InputText 
                                    id="numero" 
                                    value={devisItem.numero} 
                                    onChange={(e) => onInputChange(e, 'numero')} 
                                    placeholder="Généré automatiquement"
                                    disabled
                                />
                            </div>

                            <div className="field col-12 md:col-6">
                                <label htmlFor="client">Client</label>
                                <Dropdown 
                                    id="client" 
                                    value={devisItem.client} 
                                    options={clients} 
                                    onChange={(e) => onDropdownChange(e, 'client')} 
                                    placeholder="Sélectionnez un client"
                                    required 
                                    className={submitted && !devisItem.client ? 'p-invalid' : ''} 
                                />
                                {submitted && !devisItem.client && <small className="p-invalid">Le client est requis.</small>}
                            </div>

                            <div className="field col-12">
                                <label htmlFor="objet">Objet</label>
                                <InputText 
                                    id="objet" 
                                    value={devisItem.objet} 
                                    onChange={(e) => onInputChange(e, 'objet')} 
                                    required 
                                    className={submitted && !devisItem.objet ? 'p-invalid' : ''} 
                                    placeholder="Objet du devis"
                                />
                                {submitted && !devisItem.objet && <small className="p-invalid">L'objet est requis.</small>}
                            </div>

                            <div className="field col-12">
                                <label htmlFor="description">Description</label>
                                <InputTextarea 
                                    id="description" 
                                    value={devisItem.description} 
                                    onChange={(e) => onInputChange(e, 'description')} 
                                    rows={4} 
                                    placeholder="Description détaillée des travaux"
                                />
                            </div>

                            <div className="field col-12 md:col-6">
                                <label htmlFor="dateEmission">Date d'émission</label>
                                <Calendar
                                    id="dateEmission"
                                    value={devisItem.dateEmission ? new Date(devisItem.dateEmission) : null}
                                    onChange={(e) => onDateChange(e, 'dateEmission')}
                                    dateFormat="dd/mm/yy"
                                    showIcon
                                />
                            </div>

                            <div className="field col-12 md:col-6">
                                <label htmlFor="dateValidite">Date de validité</label>
                                <Calendar
                                    id="dateValidite"
                                    value={devisItem.dateValidite ? new Date(devisItem.dateValidite) : null}
                                    onChange={(e) => onDateChange(e, 'dateValidite')}
                                    dateFormat="dd/mm/yy"
                                    showIcon
                                    minDate={devisItem.dateEmission ? new Date(devisItem.dateEmission) : undefined}
                                />
                            </div>

                            <div className="field col-12 md:col-4">
                                <label htmlFor="montantHT">Montant HT (€)</label>
                                <InputNumber 
                                    id="montantHT" 
                                    value={devisItem.montantHT} 
                                    onValueChange={(e) => onNumberChange(e, 'montantHT')} 
                                    mode="currency" 
                                    currency="EUR" 
                                    locale="fr-FR" 
                                />
                            </div>

                            <div className="field col-12 md:col-4">
                                <label htmlFor="tauxTVA">Taux TVA (%)</label>
                                <InputNumber 
                                    id="tauxTVA" 
                                    value={devisItem.tauxTVA} 
                                    onValueChange={(e) => onNumberChange(e, 'tauxTVA')} 
                                    suffix="%" 
                                    min={0} 
                                    max={100} 
                                />
                            </div>

                            <div className="field col-12 md:col-4">
                                <label htmlFor="montantTTC">Montant TTC (€)</label>
                                <InputNumber 
                                    id="montantTTC" 
                                    value={devisItem.montantTTC} 
                                    mode="currency" 
                                    currency="EUR" 
                                    locale="fr-FR" 
                                    disabled
                                />
                            </div>

                            <div className="field col-12">
                                <label htmlFor="statut">Statut</label>
                                <Dropdown 
                                    id="statut" 
                                    value={devisItem.statut} 
                                    options={statuts} 
                                    onChange={(e) => onDropdownChange(e, 'statut')} 
                                    placeholder="Sélectionnez un statut"
                                />
                            </div>
                        </div>
                    </Dialog>

                    <Dialog 
                        visible={deleteDevisDialog} 
                        style={{ width: '450px' }} 
                        header="Confirmer" 
                        modal 
                        footer={deleteDevisDialogFooter} 
                        onHide={hideDeleteDevisDialog}
                    >
                        <div className="flex align-items-center justify-content-center">
                            <i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} />
                            {devisItem && (
                                <span>
                                    Êtes-vous sûr de vouloir supprimer le devis <b>{devisItem.numero}</b> ?
                                </span>
                            )}
                        </div>
                    </Dialog>
                </Card>
            </div>
        </div>
    );
};

export default DevisPage;