import React, { useState } from 'react';
import { Collapse } from 'react-bootstrap';
import { FileText, FileImage, FileArchive, File, Clock, ChevronDown, ChevronRight, Trash2, Download } from 'lucide-react';
import { formatCalendarDateEs, isCalendarDateBeforeToday } from '../../../utils/serverCalendarDate';

function getFileIcon(filename: string | undefined) {
    const ext = filename ? filename.split('.').pop()?.toLowerCase() : '';
    switch (ext) {
        case 'pdf':
            return (
                <div className="saas-icon-badge rose" style={{ width: '36px', height: '36px' }}>
                    <FileArchive size={18} />
                </div>
            );
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
            return (
                <div className="saas-icon-badge primary" style={{ width: '36px', height: '36px' }}>
                    <FileImage size={18} />
                </div>
            );
        case 'doc':
        case 'docx':
            return (
                <div className="saas-icon-badge indigo" style={{ width: '36px', height: '36px' }}>
                    <FileText size={18} />
                </div>
            );
        default:
            return (
                <div className="saas-icon-badge" style={{ width: '36px', height: '36px', background: '#f1f5f9', color: '#64748b', border: '1px solid #e2e8f0' }}>
                    <File size={18} />
                </div>
            );
    }
}

interface DocumentoVersion {
    id: number;
    uuid: string;
    nombre_original: string;
    fecha_carga: string;
    vence: boolean;
    fecha_vencimiento?: string | null;
}

interface DocumentoCliente {
    id: number;
    uuid: string;
    nombre_original: string;
    fecha_carga: string;
    vence: boolean;
    fecha_vencimiento?: string | null;
    tipo_documento?: {
        DesTipDoc: string;
    };
    versiones?: DocumentoVersion[];
}

interface DocumentoCardProps {
    doc: DocumentoCliente;
    onDelete?: (uuid: string) => void;
}

const DocumentoCard: React.FC<DocumentoCardProps> = ({ doc, onDelete }) => {
    const [open, setOpen] = useState(false);
    const title = doc.tipo_documento?.DesTipDoc || 'Documento';
    const isVencido = doc.fecha_vencimiento && isCalendarDateBeforeToday(doc.fecha_vencimiento);

    return (
        <div style={{
            background: '#ffffff',
            border: '1px solid #e2e8f0',
            borderRadius: '10px',
            padding: '0.75rem 0.95rem',
            marginBottom: '0.55rem',
            transition: 'all 0.15s ease'
        }}>
            <div className="d-flex justify-content-between align-items-center gap-2">
                <div className="d-flex align-items-center gap-2 flex-grow-1 text-truncate">
                    {getFileIcon(doc.nombre_original)}
                    <div className="text-truncate">
                        <div className="d-flex align-items-center gap-2 flex-wrap">
                            <span style={{ fontSize: '0.85rem', fontWeight: 700, color: '#0f172a' }} className="text-truncate" title={title}>
                                {title}
                            </span>
                            {doc.vence && (
                                <span className={`saas-badge-status ${isVencido ? 'suspended' : 'active'}`} style={{ fontSize: '0.65rem', padding: '0.1rem 0.45rem' }}>
                                    {isVencido ? 'Vencido' : 'Vence'}: {doc.fecha_vencimiento ? formatCalendarDateEs(doc.fecha_vencimiento) : 'Sin fecha'}
                                </span>
                            )}
                        </div>
                        <div style={{ fontSize: '0.72rem', color: '#64748b' }} className="d-flex align-items-center gap-1 mt-0.5">
                            <span className="text-truncate" style={{ maxWidth: '160px' }} title={doc.nombre_original}>{doc.nombre_original}</span>
                            <span>•</span>
                            <span>{doc.fecha_carga ? formatCalendarDateEs(doc.fecha_carga) : ''}</span>
                        </div>
                    </div>
                </div>

                <div className="d-flex align-items-center gap-1 flex-shrink-0">
                    <a
                        href={`/clientes/documento/descargar/${doc.uuid}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="saas-btn-ghost"
                        title="Descargar documento"
                    >
                        <Download size={14} />
                    </a>
                    {onDelete && (
                        <button
                            type="button"
                            onClick={() => onDelete(doc.uuid)}
                            className="saas-btn-ghost is-danger"
                            title="Eliminar documento"
                        >
                            <Trash2 size={14} />
                        </button>
                    )}
                    {doc.versiones && doc.versiones.length > 0 && (
                        <button
                            type="button"
                            onClick={() => setOpen(!open)}
                            className="saas-btn-ghost"
                            title={open ? 'Ocultar versiones' : 'Ver versiones'}
                        >
                            {open ? <ChevronDown size={15} /> : <ChevronRight size={15} />}
                        </button>
                    )}
                </div>
            </div>

            {/* Versiones anteriores */}
            {doc.versiones && doc.versiones.length > 0 && (
                <Collapse in={open}>
                    <div style={{ marginTop: '0.65rem', paddingTop: '0.65rem', borderTop: '1px solid #f1f5f9', paddingLeft: '0.75rem' }}>
                        <div style={{ fontSize: '0.6875rem', fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.4rem', display: 'flex', alignItems: 'center', gap: '4px' }}>
                            <Clock size={12} /> Historial ({doc.versiones.length})
                        </div>
                        <div>
                            {doc.versiones.map((ver) => (
                                <div
                                    key={ver.id}
                                    className="d-flex justify-content-between align-items-center mb-1 p-1 rounded"
                                    style={{ background: '#f8fafc', border: '1px solid #e2e8f0' }}
                                >
                                    <div className="text-truncate pe-2">
                                        <div style={{ fontSize: '0.75rem', fontWeight: 600, color: '#334155' }} className="text-truncate" title={ver.nombre_original}>
                                            {ver.nombre_original}
                                        </div>
                                        <div style={{ fontSize: '0.6875rem', color: '#94a3b8' }}>
                                            {ver.fecha_carga ? new Date(ver.fecha_carga).toLocaleDateString() : ''}
                                        </div>
                                    </div>
                                    <div className="d-flex align-items-center gap-1 flex-shrink-0">
                                        <a
                                            href={`/clientes/documento/descargar/${ver.uuid}`}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="saas-btn-ghost"
                                            style={{ padding: '0.2rem' }}
                                            title="Descargar versión"
                                        >
                                            <Download size={12} />
                                        </a>
                                        {onDelete && (
                                            <button
                                                type="button"
                                                onClick={() => onDelete(ver.uuid)}
                                                className="saas-btn-ghost is-danger"
                                                style={{ padding: '0.2rem' }}
                                                title="Eliminar versión"
                                            >
                                                <Trash2 size={12} />
                                            </button>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </Collapse>
            )}
        </div>
    );
};

export default DocumentoCard;
