import React from 'react';
import type { Note } from './types';
import { fmt } from './helpers';
import { tagStatut } from './TagStatut';

const API = '';

interface NotesTableProps {
    notes: Note[];
}

const getJustificatifUrl = (note: Note): string | null => {
    try {
        const isKmOnly = note.lignesJson
            ? JSON.parse(note.lignesJson || '[]').every((l: any) =>
                (l.categorie || '').toLowerCase().includes('kilom') &&
                parseFloat(l.montant || 0) === 0)
            : (note.km ?? 0) > 0 && parseFloat(String(note.montantTTC || 0)) === 0;
        if (isKmOnly) return 'KILOMETRIQUE';
    } catch { }

    let files: { fileName: string; uploadUrl: string }[] = note.sharepointFiles || [];
    if (!files.length && note.fichiers) {
        try { files = JSON.parse(note.fichiers); } catch { files = []; }
    }
    if (!Array.isArray(files)) files = [];

    const isApprouve = ['approuve', 'payee'].includes(note.statut || '');
    const file = files.find(f =>
        f.fileName.includes(isApprouve ? 'signe_approuve' : 'soumission')
    );
    return file?.uploadUrl || null;
};

export const NotesTable = ({ notes }: NotesTableProps) => {
    if (!notes.length) return (
        <div style={{ padding: '48px 24px', textAlign: 'center', color: 'var(--text-muted)' }}>
            <div style={{ fontSize: 36, marginBottom: 12 }}>—</div>
            <p style={{ fontSize: 14 }}>Aucune note de frais</p>
        </div>
    );

    const HEADERS = ['Référence', 'Libellé', 'Catégorie', 'Date', 'Montant TTC', 'HT', 'TVA', 'Statut', 'Justificatif'];

    return (
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
                <tr style={{ background: 'var(--bg-thead)' }}>
                    {HEADERS.map(h => (
                        <th key={h} style={{
                            padding: '10px 16px', textAlign: 'left', fontSize: 11,
                            fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase',
                            letterSpacing: '0.6px', borderBottom: '1px solid var(--border-divider)',
                        }}>{h}</th>
                    ))}
                </tr>
            </thead>
            <tbody>
                {notes.map((n, i) => (
                    <tr key={i} style={{ borderTop: '1px solid var(--border-divider)' }}>
                        <td style={{ padding: '13px 16px', color: '#6366f1', fontWeight: 700, fontFamily: 'monospace', fontSize: 12 }}>
                            {n.reference || `#${n.id}`}
                        </td>
                        <td style={{ padding: '13px 16px', fontWeight: 600, fontSize: 13, color: 'var(--text-primary)' }}>
                            {n.libelle || '—'}
                            {n.nombreParticipants && (
                                <span style={{ marginLeft: 6, fontSize: 10, background: '#fef3c7', color: '#92400e', padding: '1px 6px', borderRadius: 4 }}>
                                    {n.nombreParticipants} pers.
                                </span>
                            )}
                            {n.km && (
                                <span style={{ marginLeft: 6, fontSize: 10, background: '#ede9fe', color: '#7c3aed', padding: '1px 6px', borderRadius: 4 }}>
                                    {n.km} km
                                </span>
                            )}
                        </td>
                        <td style={{ padding: '13px 16px', fontSize: 13, color: 'var(--text-secondary)' }}>{n.categorie || '—'}</td>
                        <td style={{ padding: '13px 16px', fontSize: 12, color: 'var(--text-muted)' }}>
                            {n.date ? new Date(n.date).toLocaleDateString('fr-FR') : '—'}
                        </td>
                        <td style={{ padding: '13px 16px', fontWeight: 800, fontSize: 14, color: 'var(--text-primary)' }}>
                            {fmt(n.montant || 0)}
                        </td>
                        <td style={{ padding: '13px 16px', fontSize: 12, color: '#15803d' }}>
                            {n.montantHT ? fmt(n.montantHT) : '—'}
                        </td>
                        <td style={{ padding: '13px 16px', fontSize: 12, color: '#6366f1' }}>
                            {n.tauxTVA ? `${n.tauxTVA}%` : n.km ? 'Km' : '—'}
                        </td>
                        <td style={{ padding: '13px 16px' }}>{tagStatut(n.statut || 'brouillon')}</td>
                        <td style={{ padding: '13px 16px' }}>
                            {(() => {
                                const url = getJustificatifUrl(n);
                                if (url === 'KILOMETRIQUE')
                                    return <span style={{ color: '#7c3aed', fontSize: 12, fontWeight: 600 }}>Kilométrique</span>;
                                if (url)
                                    return (
                                        <a href={url} target="_blank" rel="noreferrer"
                                            style={{ color: '#6366f1', fontSize: 12, fontWeight: 600, textDecoration: 'none' }}>
                                            {['approuve', 'payee'].includes(n.statut || '')
                                                ? 'Justificatif approuvé'
                                                : 'Justificatif soumission'}
                                        </a>
                                    );
                                if (n.justificatif)
                                    return (
                                        <a href={`${API}/uploads/${n.justificatif}`} target="_blank" rel="noreferrer"
                                            style={{ color: '#6366f1', fontSize: 12, fontWeight: 600, textDecoration: 'none' }}>
                                            Justificatif de soumission
                                        </a>
                                    );
                                return <span style={{ color: '#cbd5e1', fontSize: 12 }}>—</span>;
                            })()}
                        </td>
                    </tr>
                ))}
            </tbody>
        </table>
    );
};
