'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 { factureService, clientService } from '../../../services/api';
import { formatDate, formatCurrency } from '../../../utils/formatters';
import { ErrorHandler } from '../../../services/errorHandler';
import type { Facture, Client } from '../../../types/btp';
import { StatutFacture, TypeFacture } from '../../../types/btp';
import { 
    ActionButtonGroup, 
    ViewButton, 
    EditButton, 
    DeleteButton,
    ActionButton
} from '../../../components/ui/ActionButton';

const FacturesPage = () => {
    const [factures, setFactures] = useState<Facture[]>([]);
    const [clients, setClients] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [selectedFactures, setSelectedFactures] = useState<Facture[]>([]);
    const [factureDialog, setFactureDialog] = useState(false);
    const [deleteFactureDialog, setDeleteFactureDialog] = useState(false);
    const [deleteFacturessDialog, setDeleteFacturessDialog] = useState(false);
    const [facture, setFacture] = useState<Facture>({
        id: '',
        numero: '',
        dateEmission: new Date().toISOString(),
        dateEcheance: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
        datePaiement: undefined,
        objet: '',
        description: '',
        montantHT: 0,
        montantTTC: 0,
        tauxTVA: 20,
        statut: StatutFacture.BROUILLON,
        typeFacture: TypeFacture.FACTURE,
        dateCreation: new Date().toISOString(),
        dateModification: new Date().toISOString(),
        actif: true,
        client: {} as Client,
        chantier: undefined,
        devis: undefined
    });
    const [submitted, setSubmitted] = useState(false);
    const toast = useRef<Toast>(null);
    const dt = useRef<DataTable<Facture[]>>(null);

    const statuts = [
        { label: 'Brouillon', value: 'BROUILLON' },
        { label: 'Émise', value: 'EMISE' },
        { label: 'Envoyée', value: 'ENVOYEE' },
        { label: 'Payée', value: 'PAYEE' },
        { label: 'En retard', value: 'EN_RETARD' },
        { label: 'Annulée', value: 'ANNULEE' }
    ];

    const types = [
        { label: 'Facture', value: 'FACTURE' },
        { label: 'Facture d\'acompte', value: 'ACOMPTE' },
        { label: 'Facture de solde', value: 'SOLDE' },
        { label: 'Avoir', value: 'AVOIR' }
    ];

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

    const loadFactures = async () => {
        try {
            setLoading(true);
            const data = await factureService.getAll();
            setFactures(data);
        } catch (error) {
            console.error('Erreur lors du chargement des factures:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger les factures',
                life: 3000
            });
        } 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) {
            console.error('Erreur lors du chargement des clients:', error);
        }
    };

    const openNew = () => {
        setFacture({
            id: '',
            numero: '',
            dateEmission: new Date().toISOString(),
            dateEcheance: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
            datePaiement: undefined,
            objet: '',
            description: '',
            montantHT: 0,
            montantTTC: 0,
            tauxTVA: 20,
            statut: StatutFacture.BROUILLON,
            typeFacture: TypeFacture.FACTURE,
            dateCreation: new Date().toISOString(),
            dateModification: new Date().toISOString(),
            actif: true,
            client: {} as Client,
            chantier: undefined,
            devis: undefined
        });
        setSubmitted(false);
        setFactureDialog(true);
    };

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

    const hideDeleteFactureDialog = () => {
        setDeleteFactureDialog(false);
    };

    const hideDeleteFacturessDialog = () => {
        setDeleteFacturessDialog(false);
    };

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

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

        if (!facture.objet.trim()) {
            validationErrors.push("L'objet de la facture est obligatoire");
        }

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

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

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

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

        if (!facture.dateEcheance || facture.dateEcheance <= facture.dateEmission) {
            validationErrors.push("La date d'échéance doit être postérieure à la date d'émission");
        }

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

        if (facture.objet.trim() && facture.client) {
            try {
                let updatedFactures = [...factures];
                const factureToSave = {
                    ...facture,
                    montantTTC: facture.montantHT * (1 + facture.tauxTVA / 100)
                };

                if (facture.id) {
                    // Mise à jour de la facture existante
                    const updatedFacture = await factureService.update(facture.id, factureToSave);
                    setFactures(factures.map(f => f.id === facture.id ? updatedFacture : f));
                    toast.current?.show({
                        severity: 'success',
                        summary: 'Succès',
                        detail: 'Facture mise à jour avec succès',
                        life: 3000
                    });
                } else {
                    // Création d'une nouvelle facture
                    const newFacture = await factureService.create(factureToSave);
                    setFactures([...factures, newFacture]);
                    toast.current?.show({
                        severity: 'success',
                        summary: 'Succès',
                        detail: 'Facture créée avec succès',
                        life: 3000
                    });
                }

                setFactureDialog(false);
                setFacture({
                    id: '',
                    numero: '',
                    dateEmission: new Date().toISOString(),
                    dateEcheance: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
                    datePaiement: undefined,
                    objet: '',
                    description: '',
                    montantHT: 0,
                    montantTTC: 0,
                    tauxTVA: 20,
                    statut: StatutFacture.BROUILLON,
                    typeFacture: TypeFacture.FACTURE,
                    dateCreation: new Date().toISOString(),
                    dateModification: new Date().toISOString(),
                    actif: true,
                    client: {} as Client,
                    chantier: undefined,
                    devis: undefined
                });
            } catch (error) {
                console.error('Erreur lors de la sauvegarde:', error);
                toast.current?.show({
                    severity: 'error',
                    summary: 'Erreur',
                    detail: 'Impossible de sauvegarder la facture',
                    life: 3000
                });
            }
        }
    };

    const editFacture = (facture: Facture) => {
        setFacture({
            ...facture
        });
        setFactureDialog(true);
    };

    const confirmDeleteFacture = (facture: Facture) => {
        setFacture(facture);
        setDeleteFactureDialog(true);
    };

    const deleteFacture = async () => {
        try {
            if (facture.id) {
                await factureService.delete(facture.id);
                setFactures(factures.filter(f => f.id !== facture.id));
                toast.current?.show({
                    severity: 'success',
                    summary: 'Succès',
                    detail: 'Facture supprimée avec succès',
                    life: 3000
                });
            }
            setDeleteFactureDialog(false);
        } catch (error) {
            console.error('Erreur lors de la suppression:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de supprimer la facture',
                life: 3000
            });
        }
    };

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

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

    const onDateChange = (e: any, name: string) => {
        let _facture = { ...facture };
        (_facture as any)[name] = e.value;
        setFacture(_facture);
    };

    const onNumberChange = (e: any, name: string) => {
        let _facture = { ...facture };
        (_facture as any)[name] = e.value;
        setFacture(_facture);

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

    const onDropdownChange = (e: any, name: string) => {
        let _facture = { ...facture };
        (_facture as any)[name] = e.value;
        setFacture(_facture);
    };

    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={() => setDeleteFacturessDialog(true)} 
                    disabled={!selectedFactures || selectedFactures.length === 0} 
                />
            </div>
        );
    };

    const rightToolbarTemplate = () => {
        return (
            <div className="flex gap-2">
                <Button 
                    label="Relances" 
                    icon="pi pi-send" 
                    severity="warning" 
                    onClick={() => {
                        toast.current?.show({
                            severity: 'info',
                            summary: 'Relances',
                            detail: 'Fonctionnalité de relance non implémentée',
                            life: 3000
                        });
                    }}
                />
                <Button 
                    label="Exporter" 
                    icon="pi pi-upload" 
                    severity="help" 
                    onClick={exportCSV} 
                />
            </div>
        );
    };

    const actionBodyTemplate = (rowData: Facture) => {
        return (
            <ActionButtonGroup>
                <ViewButton
                    tooltip="Aperçu PDF"
                    onClick={() => {
                        toast.current?.show({
                            severity: 'info',
                            summary: 'Aperçu',
                            detail: `Aperçu de la facture ${rowData.numero}`,
                            life: 3000
                        });
                    }}
                />
                <ActionButton
                    icon="pi pi-send"
                    color="blue"
                    tooltip="Envoyer par email"
                    onClick={() => {
                        toast.current?.show({
                            severity: 'info',
                            summary: 'Envoi',
                            detail: `Envoi de la facture ${rowData.numero}`,
                            life: 3000
                        });
                    }}
                />
                <EditButton
                    tooltip="Modifier"
                    onClick={() => editFacture(rowData)}
                />
                <DeleteButton
                    tooltip="Supprimer"
                    onClick={() => confirmDeleteFacture(rowData)}
                />
            </ActionButtonGroup>
        );
    };

    const statusBodyTemplate = (rowData: Facture) => {
        const getSeverity = (status: string) => {
            switch (status) {
                case 'BROUILLON': return 'secondary';
                case 'EMISE': return 'info';
                case 'ENVOYEE': return 'info';
                case 'PAYEE': return 'success';
                case 'EN_RETARD': return 'danger';
                case 'ANNULEE': return 'danger';
                default: return 'secondary';
            }
        };

        const getLabel = (status: string) => {
            switch (status) {
                case 'BROUILLON': return 'Brouillon';
                case 'EMISE': return 'Émise';
                case 'ENVOYEE': return 'Envoyée';
                case 'PAYEE': return 'Payée';
                case 'EN_RETARD': return 'En retard';
                case 'ANNULEE': return 'Annulée';
                default: return status;
            }
        };

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

    const typeBodyTemplate = (rowData: Facture) => {
        const getTypeLabel = (type: string) => {
            switch (type) {
                case 'FACTURE': return 'Facture';
                case 'ACOMPTE': return 'Acompte';
                case 'SOLDE': return 'Solde';
                case 'AVOIR': return 'Avoir';
                default: return type;
            }
        };

        return (
            <Tag
                value={getTypeLabel(rowData.typeFacture)}
                severity={rowData.typeFacture === 'AVOIR' ? 'warning' : 'info'}
            />
        );
    };

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

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

    const echeanceBodyTemplate = (rowData: Facture) => {
        const today = new Date();
        const echeanceDate = new Date(rowData.dateEcheance);
        const isOverdue = echeanceDate < today && rowData.statut !== 'PAYEE';
        
        return (
            <div className={`flex align-items-center ${isOverdue ? 'text-red-500' : ''}`}>
                {isOverdue && <i className="pi pi-exclamation-triangle mr-1"></i>}
                {formatDate(rowData.dateEcheance)}
            </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 Factures</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 factureDialogFooter = (
        <>
            <Button label="Annuler" icon="pi pi-times" text onClick={hideDialog} />
            <Button label="Sauvegarder" icon="pi pi-check" text onClick={saveFacture} />
        </>
    );

    const deleteFactureDialogFooter = (
        <>
            <Button label="Non" icon="pi pi-times" text onClick={hideDeleteFactureDialog} />
            <Button label="Oui" icon="pi pi-check" text onClick={deleteFacture} />
        </>
    );

    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="checkbox"
                        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 trouvée."
                        header={header}
                        responsiveLayout="scroll"
                        loading={loading}
                    >
                        <Column selectionMode="multiple" headerStyle={{ width: '4rem' }} />
                        <Column field="numero" header="Numéro" sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="type" header="Type" body={typeBodyTemplate} sortable headerStyle={{ minWidth: '8rem' }} />
                        <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="dateEcheance" header="Date échéance" body={echeanceBodyTemplate} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="datePaiement" header="Date paiement" body={(rowData) => dateBodyTemplate(rowData, 'datePaiement')} 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: '14rem' }} />
                    </DataTable>

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

                            <div className="field col-12 md:col-6">
                                <label htmlFor="typeFacture">Type</label>
                                <Dropdown
                                    id="typeFacture"
                                    value={facture.typeFacture}
                                    options={types}
                                    onChange={(e) => onDropdownChange(e, 'typeFacture')}
                                    placeholder="Sélectionnez un type"
                                />
                            </div>

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

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

                            <div className="field col-12">
                                <label htmlFor="objet">Objet</label>
                                <InputText 
                                    id="objet" 
                                    value={facture.objet} 
                                    onChange={(e) => onInputChange(e, 'objet')} 
                                    required 
                                    className={submitted && !facture.objet ? 'p-invalid' : ''} 
                                    placeholder="Objet de la facture"
                                />
                                {submitted && !facture.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={facture.description} 
                                    onChange={(e) => onInputChange(e, 'description')} 
                                    rows={4} 
                                    placeholder="Description détaillée des travaux facturés"
                                />
                            </div>

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

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

                            <div className="field col-12 md:col-4">
                                <label htmlFor="datePaiement">Date de paiement</label>
                                <Calendar
                                    id="datePaiement"
                                    value={facture.datePaiement ? new Date(facture.datePaiement) : null}
                                    onChange={(e) => onDateChange(e, 'datePaiement')}
                                    dateFormat="dd/mm/yy"
                                    showIcon
                                />
                            </div>

                            <div className="field col-12 md:col-4">
                                <label htmlFor="montantHT">Montant HT (€)</label>
                                <InputNumber 
                                    id="montantHT" 
                                    value={facture.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={facture.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={facture.montantTTC} 
                                    mode="currency" 
                                    currency="EUR" 
                                    locale="fr-FR" 
                                    disabled
                                />
                            </div>
                        </div>
                    </Dialog>

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

export default FacturesPage;