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


import React, { useState, useEffect, useRef } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Card } from 'primereact/card';
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext';
import { InputTextarea } from 'primereact/inputtextarea';
import { InputNumber } from 'primereact/inputnumber';
import { Dropdown } from 'primereact/dropdown';
import { Calendar } from 'primereact/calendar';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Toast } from 'primereact/toast';
import { ProgressSpinner } from 'primereact/progressspinner';
import { Toolbar } from 'primereact/toolbar';
import { Dialog } from 'primereact/dialog';
import { Divider } from 'primereact/divider';
import { factureService, clientService } from '../../../../../services/api';
import { formatCurrency } from '../../../../../utils/formatters';
import type { Facture, LigneFacture, Client } from '../../../../../types/btp';
import { StatutFacture, TypeFacture } from '../../../../../types/btp';

const FactureEditPage = () => {
    const params = useParams();
    const router = useRouter();
    const toast = useRef<Toast>(null);
    
    const [facture, setFacture] = useState<Partial<Facture>>({
        numero: '',
        objet: '',
        description: '',
        typeFacture: TypeFacture.FACTURE,
        statut: StatutFacture.BROUILLON,
        dateEmission: new Date().toISOString(),
        dateEcheance: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(), // +30 jours
        tauxTVA: 20,
        lignes: []
    });
    
    const [clients, setClients] = useState<Client[]>([]);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [showLigneDialog, setShowLigneDialog] = useState(false);
    const [editingLigne, setEditingLigne] = useState<LigneFacture | null>(null);
    const [editingIndex, setEditingIndex] = useState<number>(-1);
    
    const [ligneForm, setLigneForm] = useState<Partial<LigneFacture>>({
        designation: '',
        quantite: 1,
        unite: 'unité',
        prixUnitaire: 0,
        montantLigne: 0
    });

    const factureId = params.id as string;
    const isNew = factureId === 'nouveau';

    const typeOptions = [
        { label: 'Facture', value: 'FACTURE' },
        { label: 'Acompte', value: 'ACOMPTE' },
        { label: 'Facture de situation', value: 'SITUATION' },
        { label: 'Facture de solde', value: 'SOLDE' }
    ];

    const statutOptions = [
        { label: 'Brouillon', value: 'BROUILLON' },
        { label: 'Envoyée', value: 'ENVOYEE' },
        { label: 'Payée', value: 'PAYEE' },
        { label: 'Partiellement payée', value: 'PARTIELLEMENT_PAYEE' },
        { label: 'En retard', value: 'EN_RETARD' }
    ];

    const uniteOptions = [
        { label: 'Unité', value: 'unité' },
        { label: 'Mètre', value: 'm' },
        { label: 'Mètre carré', value: 'm²' },
        { label: 'Mètre cube', value: 'm³' },
        { label: 'Heure', value: 'h' },
        { label: 'Jour', value: 'jour' },
        { label: 'Forfait', value: 'forfait' },
        { label: 'Kilogramme', value: 'kg' },
        { label: 'Tonne', value: 't' }
    ];

    useEffect(() => {
        loadData();
    }, [factureId]);

    useEffect(() => {
        calculateMontants();
    }, [facture.lignes, facture.tauxTVA]);

    const loadData = async () => {
        try {
            setLoading(true);
            
            // Charger les clients
            const clientsResponse = await clientService.getAll();
            setClients(clientsResponse);

            if (!isNew) {
                // Charger la facture existante
                const factureResponse = await factureService.getById(factureId);
                setFacture(factureResponse);
            } else {
                // Générer un nouveau numéro basé sur la date
                const now = new Date();
                const numero = `FAC-${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}-${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`;
                setFacture(prev => ({ ...prev, numero }));
            }
            
        } catch (error) {
            console.error('Erreur lors du chargement:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger les données'
            });
        } finally {
            setLoading(false);
        }
    };

    const calculateMontants = () => {
        if (!facture.lignes) return;

        const montantHT = facture.lignes.reduce((total, ligne) => total + (ligne.montantLigne || 0), 0);
        const montantTVA = montantHT * (facture.tauxTVA || 0) / 100;
        const montantTTC = montantHT + montantTVA;

        setFacture(prev => ({
            ...prev,
            montantHT,
            montantTTC
        }));
    };

    const handleSave = async () => {
        try {
            setSaving(true);
            
            if (!facture.numero || !facture.objet || !facture.client) {
                toast.current?.show({
                    severity: 'warn',
                    summary: 'Attention',
                    detail: 'Veuillez remplir tous les champs obligatoires'
                });
                return;
            }
            
            if (isNew) {
                await factureService.create(facture);
                toast.current?.show({
                    severity: 'success',
                    summary: 'Succès',
                    detail: 'Facture créée avec succès'
                });
            } else {
                await factureService.update(factureId, facture);
                toast.current?.show({
                    severity: 'success',
                    summary: 'Succès',
                    detail: 'Facture modifiée avec succès'
                });
            }
            
            router.push('/factures');
            
        } catch (error) {
            console.error('Erreur lors de la sauvegarde:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors de la sauvegarde'
            });
        } finally {
            setSaving(false);
        }
    };

    const handleAddLigne = () => {
        setEditingLigne(null);
        setEditingIndex(-1);
        setLigneForm({
            designation: '',
            quantite: 1,
            unite: 'unité',
            prixUnitaire: 0,
            montantLigne: 0
        });
        setShowLigneDialog(true);
    };

    const handleEditLigne = (ligne: LigneFacture, index: number) => {
        setEditingLigne(ligne);
        setEditingIndex(index);
        setLigneForm({ ...ligne });
        setShowLigneDialog(true);
    };

    const handleSaveLigne = () => {
        if (!ligneForm.designation || !ligneForm.quantite || !ligneForm.prixUnitaire) {
            toast.current?.show({
                severity: 'warn',
                summary: 'Attention',
                detail: 'Veuillez remplir tous les champs de la ligne'
            });
            return;
        }
        
        const montantHT = (ligneForm.quantite || 0) * (ligneForm.prixUnitaire || 0);
        const nouvelleLigne: LigneFacture = {
            ...ligneForm,
            montantHT
        } as LigneFacture;
        
        const nouvellesLignes = [...(facture.lignes || [])];
        
        if (editingIndex >= 0) {
            nouvellesLignes[editingIndex] = nouvelleLigne;
        } else {
            nouvellesLignes.push(nouvelleLigne);
        }
        
        setFacture(prev => ({ ...prev, lignes: nouvellesLignes }));
        setShowLigneDialog(false);
    };

    const handleDeleteLigne = (index: number) => {
        const nouvellesLignes = facture.lignes?.filter((_, i) => i !== index) || [];
        setFacture(prev => ({ ...prev, lignes: nouvellesLignes }));
    };

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

    const toolbarEndTemplate = () => (
        <div className="flex align-items-center gap-2">
            <Button
                label="Annuler"
                icon="pi pi-times"
                className="p-button-outlined"
                onClick={() => router.push('/factures')}
            />
            <Button
                label="Enregistrer"
                icon="pi pi-save"
                onClick={handleSave}
                loading={saving}
            />
        </div>
    );

    if (loading) {
        return (
            <div className="flex justify-content-center align-items-center min-h-screen">
                <ProgressSpinner />
            </div>
        );
    }

    return (
        <div className="grid">
            <Toast ref={toast} />
            
            <div className="col-12">
                <Toolbar start={toolbarStartTemplate} end={toolbarEndTemplate} />
            </div>

            <div className="col-12">
                <Card title={isNew ? "Nouvelle facture" : "Modifier la facture"}>
                    <div className="grid">
                        {/* Informations générales */}
                        <div className="col-12 md:col-6">
                            <div className="field">
                                <label htmlFor="numero" className="font-semibold">Numéro *</label>
                                <InputText
                                    id="numero"
                                    value={facture.numero}
                                    onChange={(e) => setFacture(prev => ({ ...prev, numero: e.target.value }))}
                                    className="w-full"
                                    disabled={!isNew}
                                />
                            </div>
                        </div>
                        
                        <div className="col-12 md:col-6">
                            <div className="field">
                                <label htmlFor="type" className="font-semibold">Type *</label>
                                <Dropdown
                                    id="type"
                                    value={facture.typeFacture}
                                    options={typeOptions}
                                    onChange={(e) => setFacture(prev => ({ ...prev, typeFacture: e.value }))}
                                    className="w-full"
                                />
                            </div>
                        </div>
                        
                        <div className="col-12">
                            <div className="field">
                                <label htmlFor="objet" className="font-semibold">Objet *</label>
                                <InputText
                                    id="objet"
                                    value={facture.objet}
                                    onChange={(e) => setFacture(prev => ({ ...prev, objet: e.target.value }))}
                                    className="w-full"
                                />
                            </div>
                        </div>
                        
                        <div className="col-12">
                            <div className="field">
                                <label htmlFor="description" className="font-semibold">Description</label>
                                <InputTextarea
                                    id="description"
                                    value={facture.description}
                                    onChange={(e) => setFacture(prev => ({ ...prev, description: e.target.value }))}
                                    className="w-full"
                                    rows={3}
                                />
                            </div>
                        </div>
                        
                        <div className="col-12 md:col-6">
                            <div className="field">
                                <label htmlFor="client" className="font-semibold">Client *</label>
                                <Dropdown
                                    id="client"
                                    value={facture.client}
                                    options={clients.map(client => ({ label: client.nom, value: client }))}
                                    onChange={(e) => setFacture(prev => ({ ...prev, client: e.value }))}
                                    className="w-full"
                                    placeholder="Sélectionner un client"
                                    filter
                                />
                            </div>
                        </div>
                        
                        <div className="col-12 md:col-6">
                            <div className="field">
                                <label htmlFor="statut" className="font-semibold">Statut</label>
                                <Dropdown
                                    id="statut"
                                    value={facture.statut}
                                    options={statutOptions}
                                    onChange={(e) => setFacture(prev => ({ ...prev, statut: e.value }))}
                                    className="w-full"
                                />
                            </div>
                        </div>
                        
                        <div className="col-12 md:col-4">
                            <div className="field">
                                <label htmlFor="dateEmission" className="font-semibold">Date d'émission *</label>
                                <Calendar
                                    id="dateEmission"
                                    value={facture.dateEmission ? new Date(facture.dateEmission) : null}
                                    onChange={(e) => setFacture(prev => ({ ...prev, dateEmission: (e.value as Date)?.toISOString() || new Date().toISOString() }))}
                                    className="w-full"
                                    dateFormat="dd/mm/yy"
                                />
                            </div>
                        </div>
                        
                        <div className="col-12 md:col-4">
                            <div className="field">
                                <label htmlFor="dateEcheance" className="font-semibold">Date d'échéance *</label>
                                <Calendar
                                    id="dateEcheance"
                                    value={facture.dateEcheance ? new Date(facture.dateEcheance) : null}
                                    onChange={(e) => setFacture(prev => ({ ...prev, dateEcheance: (e.value as Date)?.toISOString() || new Date().toISOString() }))}
                                    className="w-full"
                                    dateFormat="dd/mm/yy"
                                />
                            </div>
                        </div>
                        
                        <div className="col-12 md:col-4">
                            <div className="field">
                                <label htmlFor="tauxTVA" className="font-semibold">Taux TVA (%)</label>
                                <InputNumber
                                    id="tauxTVA"
                                    value={facture.tauxTVA}
                                    onValueChange={(e) => setFacture(prev => ({ ...prev, tauxTVA: e.value || 0 }))}
                                    className="w-full"
                                    suffix="%"
                                    min={0}
                                    max={100}
                                />
                            </div>
                        </div>
                    </div>
                </Card>
            </div>

            {/* Lignes de la facture */}
            <div className="col-12">
                <Card>
                    <div className="flex justify-content-between align-items-center mb-4">
                        <h5 className="m-0">Lignes de facturation</h5>
                        <Button
                            label="Ajouter une ligne"
                            icon="pi pi-plus"
                            onClick={handleAddLigne}
                        />
                    </div>
                    
                    <DataTable 
                        value={facture.lignes || []} 
                        responsiveLayout="scroll"
                        emptyMessage="Aucune ligne de facturation"
                    >
                        <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)}
                        />
                        <Column 
                            header="Actions" 
                            style={{ width: '100px' }}
                            body={(rowData, options) => (
                                <div className="flex gap-1">
                                    <Button
                                        icon="pi pi-pencil"
                                        className="p-button-text p-button-sm"
                                        onClick={() => handleEditLigne(rowData, options.rowIndex)}
                                    />
                                    <Button
                                        icon="pi pi-trash"
                                        className="p-button-text p-button-sm p-button-danger"
                                        onClick={() => handleDeleteLigne(options.rowIndex)}
                                    />
                                </div>
                            )}
                        />
                    </DataTable>
                    
                    <Divider />
                    
                    {/* Totaux */}
                    <div className="flex justify-content-end">
                        <div className="w-20rem">
                            <div className="flex justify-content-between mb-2">
                                <span>Montant HT:</span>
                                <span className="font-semibold">{formatCurrency(facture.montantHT || 0)}</span>
                            </div>
                            <div className="flex justify-content-between mb-2">
                                <span>TVA ({facture.tauxTVA}%):</span>
                                <span className="font-semibold">
                                    {formatCurrency(((facture.montantHT || 0) * (facture.tauxTVA || 0)) / 100)}
                                </span>
                            </div>
                            <Divider />
                            <div className="flex justify-content-between">
                                <span className="font-bold">Montant TTC:</span>
                                <span className="font-bold text-primary text-xl">
                                    {formatCurrency(facture.montantTTC || 0)}
                                </span>
                            </div>
                        </div>
                    </div>
                </Card>
            </div>

            {/* Dialog d'ajout/modification de ligne */}
            <Dialog
                header={editingLigne ? "Modifier la ligne" : "Ajouter une ligne"}
                visible={showLigneDialog}
                onHide={() => setShowLigneDialog(false)}
                style={{ width: '600px' }}
                footer={
                    <div className="flex justify-content-end gap-2">
                        <Button
                            label="Annuler"
                            icon="pi pi-times"
                            className="p-button-outlined"
                            onClick={() => setShowLigneDialog(false)}
                        />
                        <Button
                            label="Enregistrer"
                            icon="pi pi-save"
                            onClick={handleSaveLigne}
                        />
                    </div>
                }
            >
                <div className="grid">
                    <div className="col-12">
                        <div className="field">
                            <label htmlFor="designation" className="font-semibold">Désignation *</label>
                            <InputText
                                id="designation"
                                value={ligneForm.designation}
                                onChange={(e) => setLigneForm(prev => ({ ...prev, designation: e.target.value }))}
                                className="w-full"
                            />
                        </div>
                    </div>
                    
                    <div className="col-12 md:col-4">
                        <div className="field">
                            <label htmlFor="quantite" className="font-semibold">Quantité *</label>
                            <InputNumber
                                id="quantite"
                                value={ligneForm.quantite}
                                onValueChange={(e) => {
                                    const quantite = e.value || 0;
                                    const montantHT = quantite * (ligneForm.prixUnitaire || 0);
                                    setLigneForm(prev => ({ ...prev, quantite, montantHT }));
                                }}
                                className="w-full"
                                min={0}
                                maxFractionDigits={2}
                            />
                        </div>
                    </div>
                    
                    <div className="col-12 md:col-4">
                        <div className="field">
                            <label htmlFor="unite" className="font-semibold">Unité</label>
                            <Dropdown
                                id="unite"
                                value={ligneForm.unite}
                                options={uniteOptions}
                                onChange={(e) => setLigneForm(prev => ({ ...prev, unite: e.value }))}
                                className="w-full"
                            />
                        </div>
                    </div>
                    
                    <div className="col-12 md:col-4">
                        <div className="field">
                            <label htmlFor="prixUnitaire" className="font-semibold">Prix unitaire *</label>
                            <InputNumber
                                id="prixUnitaire"
                                value={ligneForm.prixUnitaire}
                                onValueChange={(e) => {
                                    const prixUnitaire = e.value || 0;
                                    const montantHT = (ligneForm.quantite || 0) * prixUnitaire;
                                    setLigneForm(prev => ({ ...prev, prixUnitaire, montantHT }));
                                }}
                                className="w-full"
                                mode="currency"
                                currency="EUR"
                                locale="fr-FR"
                                min={0}
                            />
                        </div>
                    </div>
                    
                    <div className="col-12">
                        <div className="field">
                            <label className="font-semibold">Montant HT</label>
                            <div className="text-xl font-bold text-primary">
                                {formatCurrency(ligneForm.montantLigne || 0)}
                            </div>
                        </div>
                    </div>
                </div>
            </Dialog>
        </div>
    );
};

export default FactureEditPage;
