'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 { 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 { Divider } from 'primereact/divider';
import { Checkbox } from 'primereact/checkbox';
import { factureService, clientService } from '../../../../../services/api';
import { formatCurrency } from '../../../../../utils/formatters';
import type { Facture, Client } from '../../../../../types/btp';
import { StatutFacture, TypeFacture } from '../../../../../types/btp';

const FactureDuplicatePage = () => {
    const params = useParams();
    const router = useRouter();
    const toast = useRef<Toast>(null);
    
    const [originalFacture, setOriginalFacture] = useState<Facture | null>(null);
    const [newFacture, setNewFacture] = 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 [copyLignes, setCopyLignes] = useState(true);
    const [copyClient, setCopyClient] = useState(true);

    const factureId = params.id as string;

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

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

    useEffect(() => {
        if (originalFacture) {
            updateNewFacture();
        }
    }, [originalFacture, copyLignes, copyClient]);

    const loadData = async () => {
        try {
            setLoading(true);
            
            // Charger la facture originale
            const factureResponse = await factureService.getById(factureId);
            setOriginalFacture(factureResponse);

            // Charger les clients
            const clientsResponse = await clientService.getAll();
            setClients(clientsResponse);

            // 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')}`;
            setNewFacture(prev => ({ ...prev, numero }));
            
        } catch (error) {
            console.error('Erreur lors du chargement:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger la facture'
            });
        } finally {
            setLoading(false);
        }
    };

    const updateNewFacture = () => {
        if (!originalFacture) return;

        setNewFacture(prev => ({
            ...prev,
            objet: `${originalFacture.objet} (Copie)`,
            description: originalFacture.description,
            typeFacture: originalFacture.typeFacture,
            tauxTVA: originalFacture.tauxTVA,
            client: copyClient ? originalFacture.client : undefined,
            lignes: copyLignes ? [...(originalFacture.lignes || [])] : [],
            montantHT: copyLignes ? originalFacture.montantHT : 0,
            montantTTC: copyLignes ? originalFacture.montantTTC : 0
        }));
    };

    const handleSave = async () => {
        try {
            setSaving(true);
            
            if (!newFacture.numero || !newFacture.objet || !newFacture.client) {
                toast.current?.show({
                    severity: 'warn',
                    summary: 'Attention',
                    detail: 'Veuillez remplir tous les champs obligatoires'
                });
                return;
            }
            
            await factureService.create(newFacture);
            
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Facture dupliquée avec succès'
            });
            
            router.push('/factures');
            
        } catch (error) {
            console.error('Erreur lors de la duplication:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors de la duplication'
            });
        } 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(`/factures/${factureId}`)}
            />
        </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/${factureId}`)}
            />
            <Button
                label="Créer la copie"
                icon="pi pi-copy"
                onClick={handleSave}
                loading={saving}
            />
        </div>
    );

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

    if (!originalFacture) {
        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>Facture introuvable</h3>
                    <p className="text-600 mb-4">La facture à dupliquer n'existe pas</p>
                    <Button
                        label="Retour à la liste"
                        icon="pi pi-arrow-left"
                        onClick={() => router.push('/factures')}
                    />
                </div>
            </div>
        );
    }

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

            <div className="col-12">
                <Card title="Dupliquer la facture">
                    <div className="grid">
                        {/* Options de duplication */}
                        <div className="col-12">
                            <h5>Options de duplication</h5>
                            <div className="flex gap-4 mb-4">
                                <div className="flex align-items-center">
                                    <Checkbox
                                        inputId="copyClient"
                                        checked={copyClient}
                                        onChange={(e) => setCopyClient(e.checked || false)}
                                    />
                                    <label htmlFor="copyClient" className="ml-2">Copier le client</label>
                                </div>
                                <div className="flex align-items-center">
                                    <Checkbox
                                        inputId="copyLignes"
                                        checked={copyLignes}
                                        onChange={(e) => setCopyLignes(e.checked || false)}
                                    />
                                    <label htmlFor="copyLignes" className="ml-2">Copier les lignes de facturation</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </Card>
            </div>

            {/* Comparaison côte à côte */}
            <div className="col-12 lg:col-6">
                <Card title="Facture originale" className="h-full">
                    <div className="mb-3">
                        <strong>Numéro:</strong> {originalFacture.numero}
                    </div>
                    <div className="mb-3">
                        <strong>Objet:</strong> {originalFacture.objet}
                    </div>
                    <div className="mb-3">
                        <strong>Type:</strong> {originalFacture.typeFacture}
                    </div>
                    <div className="mb-3">
                        <strong>Client:</strong> {typeof originalFacture.client === 'string' ? originalFacture.client : originalFacture.client?.nom}
                    </div>
                    <div className="mb-3">
                        <strong>Montant TTC:</strong> {formatCurrency(originalFacture.montantTTC)}
                    </div>
                    <div className="mb-3">
                        <strong>Nombre de lignes:</strong> {originalFacture.lignes?.length || 0}
                    </div>
                    {originalFacture.description && (
                        <div className="mb-3">
                            <strong>Description:</strong>
                            <p className="mt-1 text-600">{originalFacture.description}</p>
                        </div>
                    )}
                </Card>
            </div>

            <div className="col-12 lg:col-6">
                <Card title="Nouvelle facture" className="h-full">
                    <div className="grid">
                        <div className="col-12">
                            <div className="field">
                                <label htmlFor="numero" className="font-semibold">Numéro *</label>
                                <InputText
                                    id="numero"
                                    value={newFacture.numero}
                                    onChange={(e) => setNewFacture(prev => ({ ...prev, numero: e.target.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={newFacture.objet}
                                    onChange={(e) => setNewFacture(prev => ({ ...prev, objet: e.target.value }))}
                                    className="w-full"
                                />
                            </div>
                        </div>
                        
                        <div className="col-12">
                            <div className="field">
                                <label htmlFor="type" className="font-semibold">Type *</label>
                                <Dropdown
                                    id="type"
                                    value={newFacture.typeFacture}
                                    options={typeOptions}
                                    onChange={(e) => setNewFacture(prev => ({ ...prev, typeFacture: e.value }))}
                                    className="w-full"
                                />
                            </div>
                        </div>
                        
                        <div className="col-12">
                            <div className="field">
                                <label htmlFor="client" className="font-semibold">Client *</label>
                                <Dropdown
                                    id="client"
                                    value={newFacture.client}
                                    options={clients.map(client => ({ label: client.nom, value: client }))}
                                    onChange={(e) => setNewFacture(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="dateEmission" className="font-semibold">Date d'émission *</label>
                                <Calendar
                                    id="dateEmission"
                                    value={newFacture.dateEmission ? new Date(newFacture.dateEmission) : null}
                                    onChange={(e) => setNewFacture(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-6">
                            <div className="field">
                                <label htmlFor="dateEcheance" className="font-semibold">Date d'échéance *</label>
                                <Calendar
                                    id="dateEcheance"
                                    value={newFacture.dateEcheance ? new Date(newFacture.dateEcheance) : null}
                                    onChange={(e) => setNewFacture(prev => ({ ...prev, dateEcheance: (e.value as Date)?.toISOString() || new Date().toISOString() }))}
                                    className="w-full"
                                    dateFormat="dd/mm/yy"
                                />
                            </div>
                        </div>
                        
                        <div className="col-12">
                            <div className="field">
                                <label htmlFor="description" className="font-semibold">Description</label>
                                <InputTextarea
                                    id="description"
                                    value={newFacture.description}
                                    onChange={(e) => setNewFacture(prev => ({ ...prev, description: e.target.value }))}
                                    className="w-full"
                                    rows={3}
                                />
                            </div>
                        </div>
                    </div>
                </Card>
            </div>

            {/* Aperçu des lignes copiées */}
            {copyLignes && newFacture.lignes && newFacture.lignes.length > 0 && (
                <div className="col-12">
                    <Card title="Lignes de facturation copiées">
                        <DataTable value={newFacture.lignes} responsiveLayout="scroll">
                            <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>
                        
                        <Divider />
                        
                        <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(newFacture.montantHT || 0)}</span>
                                </div>
                                <div className="flex justify-content-between mb-2">
                                    <span>TVA ({newFacture.tauxTVA}%):</span>
                                    <span className="font-semibold">
                                        {formatCurrency(((newFacture.montantHT || 0) * (newFacture.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(newFacture.montantTTC || 0)}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </Card>
                </div>
            )}

            {/* Résumé de la duplication */}
            <div className="col-12">
                <Card>
                    <div className="grid">
                        <div className="col-12 md:col-4">
                            <div className="p-3 border-round bg-blue-50">
                                <h6 className="text-blue-900 mb-2">
                                    <i className="pi pi-info-circle mr-2"></i>
                                    Informations copiées
                                </h6>
                                <ul className="text-sm text-blue-800 list-none p-0 m-0">
                                    <li className="mb-1">• Objet (modifié)</li>
                                    <li className="mb-1">• Type de facture</li>
                                    <li className="mb-1">• Taux de TVA</li>
                                    <li className="mb-1">• Description</li>
                                    {copyClient && <li className="mb-1">• Client</li>}
                                    {copyLignes && <li className="mb-1">• Lignes de facturation</li>}
                                </ul>
                            </div>
                        </div>
                        
                        <div className="col-12 md:col-4">
                            <div className="p-3 border-round bg-green-50">
                                <h6 className="text-green-900 mb-2">
                                    <i className="pi pi-check mr-2"></i>
                                    Nouvelles valeurs
                                </h6>
                                <ul className="text-sm text-green-800 list-none p-0 m-0">
                                    <li className="mb-1">• Nouveau numéro généré</li>
                                    <li className="mb-1">• Statut: Brouillon</li>
                                    <li className="mb-1">• Date d'émission: Aujourd'hui</li>
                                    <li className="mb-1">• Date d'échéance: +30 jours</li>
                                    <li className="mb-1">• Montants payés: Remis à zéro</li>
                                </ul>
                            </div>
                        </div>
                        
                        <div className="col-12 md:col-4">
                            <div className="p-3 border-round bg-orange-50">
                                <h6 className="text-orange-900 mb-2">
                                    <i className="pi pi-exclamation-triangle mr-2"></i>
                                    À vérifier
                                </h6>
                                <ul className="text-sm text-orange-800 list-none p-0 m-0">
                                    <li className="mb-1">• Objet de la facture</li>
                                    <li className="mb-1">• Client sélectionné</li>
                                    <li className="mb-1">• Dates d'émission et d'échéance</li>
                                    <li className="mb-1">• Lignes de facturation</li>
                                    <li className="mb-1">• Montants calculés</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </Card>
            </div>
        </div>
    );
};

export default FactureDuplicatePage;
