'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 { Calendar } from 'primereact/calendar';
import { Dropdown } from 'primereact/dropdown';
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 { devisService, clientService } from '../../../../../services/api';
import { formatCurrency } from '../../../../../utils/formatters';
import type { Devis, LigneDevis } from '../../../../../types/btp';
import { StatutDevis } from '../../../../../types/btp';

const EditDevisPage = () => {
    const params = useParams();
    const router = useRouter();
    const toast = useRef<Toast>(null);
    
    const [devis, setDevis] = 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: StatutDevis.BROUILLON,
        actif: true,
        lignes: []
    });
    
    const [clients, setClients] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [showLigneDialog, setShowLigneDialog] = useState(false);
    const [editingLigne, setEditingLigne] = useState<any>(null);
    const [nouvelleLigne, setNouvelleLigne] = useState<Partial<LigneDevis>>({
        designation: '',
        quantite: 1,
        unite: 'unité',
        prixUnitaire: 0,
        montantLigne: 0
    });

    const devisId = params.id as string;

    const statutOptions = [
        { label: 'Brouillon', value: 'BROUILLON' },
        { label: 'En attente', value: 'EN_ATTENTE' },
        { label: 'Accepté', value: 'ACCEPTE' },
        { label: 'Refusé', value: 'REFUSE' },
        { label: 'Expiré', value: 'EXPIRE' }
    ];

    const uniteOptions = [
        { label: 'Unité', value: 'unité' },
        { label: 'Heure', value: 'heure' },
        { label: 'Jour', value: 'jour' },
        { label: 'M²', value: 'm²' },
        { label: 'M³', value: 'm³' },
        { label: 'ML', value: 'ml' },
        { label: 'Kg', value: 'kg' },
        { label: 'Tonne', value: 'tonne' },
        { label: 'Forfait', value: 'forfait' }
    ];

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

    const loadData = async () => {
        try {
            setLoading(true);
            const [devisData, clientsData] = await Promise.all([
                devisService.getById(devisId),
                clientService.getAll()
            ]);

            setDevis(devisData);
            setClients(clientsData);
        } 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 = () => {
        const montantHT = (devis.lignes || []).reduce((sum, ligne) => sum + (ligne.montantLigne || 0), 0);
        const montantTTC = montantHT * (1 + (devis.tauxTVA || 0) / 100);
        
        setDevis(prev => ({
            ...prev,
            montantHT,
            montantTTC
        }));
    };

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

    const handleSave = async () => {
        try {
            setSaving(true);
            await devisService.update(devisId, devis);
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Devis modifié avec succès'
            });
            router.push(`/devis/${devisId}`);
        } 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);
        setNouvelleLigne({
            designation: '',
            quantite: 1,
            unite: 'unité',
            prixUnitaire: 0,
            montantLigne: 0
        });
        setShowLigneDialog(true);
    };

    const handleEditLigne = (ligne: LigneDevis, index: number) => {
        setEditingLigne({ ...ligne, index });
        setNouvelleLigne({ ...ligne });
        setShowLigneDialog(true);
    };

    const handleSaveLigne = () => {
        const montantLigne = (nouvelleLigne.quantite || 0) * (nouvelleLigne.prixUnitaire || 0);
        const ligneComplete = { ...nouvelleLigne, montantLigne };

        const nouvelleLignes = [...(devis.lignes || [])] as any[];

        if (editingLigne && editingLigne.index !== undefined) {
            nouvelleLignes[editingLigne.index] = ligneComplete;
        } else {
            nouvelleLignes.push(ligneComplete);
        }
        
        setDevis(prev => ({ ...prev, lignes: nouvelleLignes }));
        setShowLigneDialog(false);
    };

    const handleDeleteLigne = (index: number) => {
        const nouvelleLignes = [...(devis.lignes || [])];
        nouvelleLignes.splice(index, 1);
        setDevis(prev => ({ ...prev, lignes: nouvelleLignes }));
    };

    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/${devisId}`)}
            />
        </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(`/devis/${devisId}`)}
            />
            <Button
                label="Enregistrer"
                icon="pi pi-save"
                loading={saving}
                onClick={handleSave}
            />
        </div>
    );

    const actionBodyTemplate = (rowData: LigneDevis, options: any) => (
        <div className="flex gap-2">
            <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>
    );

    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>

            {/* Informations générales */}
            <div className="col-12">
                <Card title="Informations générales">
                    <div className="grid">
                        <div className="col-12 md:col-6">
                            <div className="field">
                                <label htmlFor="numero" className="font-semibold">Numéro *</label>
                                <InputText
                                    id="numero"
                                    value={devis.numero}
                                    onChange={(e) => setDevis(prev => ({ ...prev, numero: e.target.value }))}
                                    className="w-full"
                                    required
                                />
                            </div>
                            
                            <div className="field">
                                <label htmlFor="objet" className="font-semibold">Objet *</label>
                                <InputText
                                    id="objet"
                                    value={devis.objet}
                                    onChange={(e) => setDevis(prev => ({ ...prev, objet: e.target.value }))}
                                    className="w-full"
                                    required
                                />
                            </div>
                            
                            <div className="field">
                                <label htmlFor="client" className="font-semibold">Client *</label>
                                <Dropdown
                                    id="client"
                                    value={devis.client?.id}
                                    options={clients}
                                    onChange={(e) => {
                                        const selectedClient = clients.find(c => c.id === e.value);
                                        setDevis(prev => ({ ...prev, client: selectedClient }));
                                    }}
                                    optionLabel="nom"
                                    optionValue="id"
                                    placeholder="Sélectionner un client"
                                    className="w-full"
                                    filter
                                />
                            </div>
                        </div>
                        
                        <div className="col-12 md:col-6">
                            <div className="field">
                                <label htmlFor="dateEmission" className="font-semibold">Date d'émission *</label>
                                <Calendar
                                    id="dateEmission"
                                    value={new Date(devis.dateEmission)}
                                    onChange={(e) => setDevis(prev => ({ ...prev, dateEmission: e.value?.toISOString() || new Date().toISOString() }))}
                                    className="w-full"
                                    dateFormat="dd/mm/yy"
                                />
                            </div>
                            
                            <div className="field">
                                <label htmlFor="dateValidite" className="font-semibold">Date de validité *</label>
                                <Calendar
                                    id="dateValidite"
                                    value={new Date(devis.dateValidite)}
                                    onChange={(e) => setDevis(prev => ({ ...prev, dateValidite: e.value?.toISOString() || new Date().toISOString() }))}
                                    className="w-full"
                                    dateFormat="dd/mm/yy"
                                />
                            </div>
                            
                            <div className="field">
                                <label htmlFor="statut" className="font-semibold">Statut</label>
                                <Dropdown
                                    id="statut"
                                    value={devis.statut}
                                    options={statutOptions}
                                    onChange={(e) => setDevis(prev => ({ ...prev, statut: e.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={devis.description}
                                    onChange={(e) => setDevis(prev => ({ ...prev, description: e.target.value }))}
                                    className="w-full"
                                    rows={4}
                                />
                            </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={devis.tauxTVA}
                                    onValueChange={(e) => setDevis(prev => ({ ...prev, tauxTVA: e.value || 0 }))}
                                    className="w-full"
                                    suffix="%"
                                    min={0}
                                    max={100}
                                />
                            </div>
                        </div>
                    </div>
                </Card>
            </div>

            {/* Lignes du devis */}
            <div className="col-12">
                <Card 
                    title="Prestations"
                    subTitle={`Total HT: ${formatCurrency(devis.montantHT)} | Total TTC: ${formatCurrency(devis.montantTTC)}`}
                >
                    <div className="mb-3">
                        <Button
                            label="Ajouter une ligne"
                            icon="pi pi-plus"
                            onClick={handleAddLigne}
                        />
                    </div>
                    
                    <DataTable 
                        value={devis.lignes || []} 
                        responsiveLayout="scroll"
                        emptyMessage="Aucune prestation ajoutée"
                    >
                        <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={actionBodyTemplate}
                        />
                    </DataTable>
                </Card>
            </div>

            {/* Dialog pour ajouter/modifier une ligne */}
            <Dialog
                header={editingLigne ? "Modifier la prestation" : "Ajouter une prestation"}
                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={nouvelleLigne.designation}
                                onChange={(e) => setNouvelleLigne(prev => ({ ...prev, designation: e.target.value }))}
                                className="w-full"
                                required
                            />
                        </div>
                    </div>
                    
                    <div className="col-12 md:col-4">
                        <div className="field">
                            <label htmlFor="quantite" className="font-semibold">Quantité *</label>
                            <InputNumber
                                id="quantite"
                                value={nouvelleLigne.quantite}
                                onValueChange={(e) => setNouvelleLigne(prev => ({ ...prev, quantite: e.value || 0 }))}
                                className="w-full"
                                min={0}
                                required
                            />
                        </div>
                    </div>
                    
                    <div className="col-12 md:col-4">
                        <div className="field">
                            <label htmlFor="unite" className="font-semibold">Unité</label>
                            <Dropdown
                                id="unite"
                                value={nouvelleLigne.unite}
                                options={uniteOptions}
                                onChange={(e) => setNouvelleLigne(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={nouvelleLigne.prixUnitaire}
                                onValueChange={(e) => setNouvelleLigne(prev => ({ ...prev, prixUnitaire: e.value || 0 }))}
                                className="w-full"
                                mode="currency"
                                currency="EUR"
                                locale="fr-FR"
                                min={0}
                                required
                            />
                        </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(nouvelleLigne.quantite * nouvelleLigne.prixUnitaire)}
                            </div>
                        </div>
                    </div>
                </div>
            </Dialog>
        </div>
    );
};

export default EditDevisPage;
