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

const DuplicateDevisPage = () => {
    const params = useParams();
    const router = useRouter();
    const toast = useRef<Toast>(null);
    
    const [originalDevis, setOriginalDevis] = useState<Devis | null>(null);
    const [newDevis, setNewDevis] = 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 originalDevisId = params.id as string;

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

    const loadData = async () => {
        try {
            setLoading(true);
            const [original, clients] = await Promise.all([
                devisService.getById(originalDevisId),
                clientService.getAll()
            ]);

            setOriginalDevis(original);
            setClients(clients);
            
            // Générer un nouveau numéro de devis
            const newNumero = await generateNewNumero();
            
            // Préparer le nouveau devis avec les données de l'original
            setNewDevis({
                id: '',
                numero: newNumero,
                dateEmission: new Date().toISOString(),
                dateValidite: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
                objet: `${original.objet} (Copie)`,
                description: original.description,
                montantHT: original.montantHT,
                montantTTC: original.montantTTC,
                tauxTVA: original.tauxTVA,
                statut: StatutDevis.BROUILLON,
                actif: true,
                client: original.client,
                lignes: original.lignes ? [...original.lignes] : []
            });
            
        } catch (error) {
            console.error('Erreur lors du chargement:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger le devis original'
            });
        } finally {
            setLoading(false);
        }
    };

    const generateNewNumero = async (): Promise<string> => {
        try {
            // TODO: Implémenter la génération automatique de numéro
            const year = new Date().getFullYear();
            const timestamp = Date.now().toString().slice(-6);
            return `DEV-${year}-${timestamp}`;
        } catch (error) {
            console.error('Erreur génération numéro:', error);
            return `DEV-${Date.now()}`;
        }
    };

    const calculateMontants = () => {
        const montantHT = (newDevis.lignes || []).reduce((sum, ligne) => sum + (ligne.montantLigne || 0), 0);
        const montantTTC = montantHT * (1 + (newDevis.tauxTVA || 0) / 100);
        
        setNewDevis(prev => ({
            ...prev,
            montantHT,
            montantTTC
        }));
    };

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

    const handleSave = async () => {
        try {
            setSaving(true);
            
            // Validation
            if (!newDevis.numero || !newDevis.objet || !newDevis.client) {
                toast.current?.show({
                    severity: 'warn',
                    summary: 'Attention',
                    detail: 'Veuillez remplir tous les champs obligatoires'
                });
                return;
            }
            
            const createdDevis = await devisService.create(newDevis);

            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Devis dupliqué avec succès'
            });

            router.push(`/devis/${createdDevis.id}`);
            
        } catch (error) {
            console.error('Erreur lors de la duplication:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors de la duplication du devis'
            });
        } finally {
            setSaving(false);
        }
    };

    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/${originalDevisId}`)}
            />
        </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/${originalDevisId}`)}
            />
            <Button
                label="Créer la copie"
                icon="pi pi-copy"
                loading={saving}
                onClick={handleSave}
            />
        </div>
    );

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

    if (!originalDevis) {
        return (
            <div className="flex justify-content-center align-items-center min-h-screen">
                <div className="text-center">
                    <i className="pi pi-exclamation-triangle text-6xl text-orange-500 mb-3"></i>
                    <h3>Devis introuvable</h3>
                    <p className="text-600 mb-4">Le devis à dupliquer n'existe pas</p>
                    <Button
                        label="Retour à la liste"
                        icon="pi pi-arrow-left"
                        onClick={() => router.push('/devis')}
                    />
                </div>
            </div>
        );
    }

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

            {/* Message d'information */}
            <div className="col-12">
                <Message 
                    severity="info" 
                    text={`Duplication du devis #${originalDevis.numero}. Vous pouvez modifier les informations avant de créer la copie.`}
                    className="w-full"
                />
            </div>

            {/* Comparaison Original vs Nouveau */}
            <div className="col-12">
                <Card title="Comparaison">
                    <div className="grid">
                        <div className="col-12 md:col-6">
                            <h5 className="text-primary">Devis original</h5>
                            <div className="field">
                                <label className="font-semibold">Numéro:</label>
                                <p>{originalDevis.numero}</p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">Objet:</label>
                                <p>{originalDevis.objet}</p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">Montant TTC:</label>
                                <p className="text-xl font-bold">{formatCurrency(originalDevis.montantTTC)}</p>
                            </div>
                        </div>
                        
                        <div className="col-12 md:col-6">
                            <h5 className="text-green-500">Nouveau devis</h5>
                            <div className="field">
                                <label className="font-semibold">Numéro:</label>
                                <p className="text-green-600 font-semibold">{newDevis.numero}</p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">Objet:</label>
                                <p className="text-green-600">{newDevis.objet}</p>
                            </div>
                            <div className="field">
                                <label className="font-semibold">Montant TTC:</label>
                                <p className="text-xl font-bold text-green-600">{formatCurrency(newDevis.montantTTC)}</p>
                            </div>
                        </div>
                    </div>
                </Card>
            </div>

            {/* Informations du nouveau devis */}
            <div className="col-12">
                <Card title="Informations du nouveau devis">
                    <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={newDevis.numero}
                                    onChange={(e) => setNewDevis(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={newDevis.objet}
                                    onChange={(e) => setNewDevis(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={newDevis.client?.id}
                                    options={clients}
                                    onChange={(e) => {
                                        const selectedClient = clients.find(c => c.id === e.value);
                                        setNewDevis(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(newDevis.dateEmission)}
                                    onChange={(e) => setNewDevis(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(newDevis.dateValidite)}
                                    onChange={(e) => setNewDevis(prev => ({ ...prev, dateValidite: e.value?.toISOString() || new Date().toISOString() }))}
                                    className="w-full"
                                    dateFormat="dd/mm/yy"
                                />
                            </div>
                            
                            <div className="field">
                                <label className="font-semibold">Statut</label>
                                <p className="text-600">Brouillon (par défaut pour les nouveaux devis)</p>
                            </div>
                        </div>
                        
                        <div className="col-12">
                            <div className="field">
                                <label htmlFor="description" className="font-semibold">Description</label>
                                <InputTextarea
                                    id="description"
                                    value={newDevis.description}
                                    onChange={(e) => setNewDevis(prev => ({ ...prev, description: e.target.value }))}
                                    className="w-full"
                                    rows={4}
                                />
                            </div>
                        </div>
                    </div>
                </Card>
            </div>

            {/* Prestations copiées */}
            <div className="col-12">
                <Card 
                    title="Prestations copiées"
                    subTitle={`${newDevis.lignes?.length || 0} ligne(s) | Total TTC: ${formatCurrency(newDevis.montantTTC)}`}
                >
                    <DataTable 
                        value={newDevis.lignes || []} 
                        responsiveLayout="scroll"
                        emptyMessage="Aucune prestation copié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)}
                        />
                    </DataTable>
                    
                    <div className="mt-3 p-3 bg-blue-50 border-round">
                        <p className="text-sm text-600 mb-2">
                            <i className="pi pi-info-circle mr-2"></i>
                            Les prestations ont été copiées depuis le devis original. 
                            Vous pourrez les modifier après la création du nouveau devis.
                        </p>
                        <div className="flex justify-content-between align-items-center">
                            <span className="font-semibold">Total HT: {formatCurrency(newDevis.montantHT)}</span>
                            <span className="font-semibold text-primary">Total TTC: {formatCurrency(newDevis.montantTTC)}</span>
                        </div>
                    </div>
                </Card>
            </div>
        </div>
    );
};

export default DuplicateDevisPage;
