import { Documento } from "@/types/document";
import { Row } from "@tanstack/react-table";
import { flexRender } from "@tanstack/react-table";
import { LuUser, LuCalendar, LuFileText, LuEye, LuTrash2, LuFolderOpen } from "react-icons/lu";
import { useState } from "react";

interface MobileDocumentCardProps {
    row: Row<Documento>;
    onDelete: (doc: Documento) => void;
    onView: (doc: Documento) => void;
}

export default function MobileDocumentCard({ row, onDelete, onView }: MobileDocumentCardProps) {
    const doc = row.original;
    const [isExpanded, setIsExpanded] = useState(false);

    // Helper to get formatted values safely
    const getValue = (columnId: string) => {
        return row.getValue(columnId);
    };

    const category = doc.category;
    const employeeName = doc.owner?.name || doc.owner?.username || "Desconocido";

    // Try to find common fields in extractedData for preview
    const extracted = doc.extractedData as Record<string, any> || {};
    const total = extracted.total || extracted.totalGeneral || extracted.TOTAL || extracted.montoTotal;
    const date = extracted.fecha || extracted.date || extracted.FECHA || new Date(doc.createdAt).toLocaleDateString();

    return (
        <div className="bg-background p-4 rounded-xl border border-border-subtle shadow-sm space-y-3">
            {/* Header: Icon, Name, Options */}
            <div className="flex items-start justify-between gap-3">
                <div className="flex items-center gap-3 overflow-hidden">
                    <div className="p-2 bg-primary-faint rounded-lg shrink-0">
                        <LuFileText className="h-5 w-5 text-primary" />
                    </div>
                    <div className="min-w-0">
                        <h3 className="font-medium text-text truncate">
                            {String(getValue("NOMBRE") || "Documento sin nombre")}
                        </h3>
                        <p className="text-xs text-text-muted flex items-center gap-1 mt-0.5">
                            <LuCalendar className="h-3 w-3" />
                            {String(date)}
                        </p>
                    </div>
                </div>

                {/* Actions Dropdown or simple buttons */}
                <div className="flex items-center gap-1">
                    <button
                        onClick={() => onView(doc)}
                        className="p-2 text-text-subtle hover:text-primary hover:bg-primary-faint rounded-lg transition-colors"
                    >
                        <LuEye className="h-5 w-5" />
                    </button>
                    <button
                        onClick={() => onDelete(doc)}
                        className="p-2 text-text-subtle hover:text-destructive hover:bg-destructive-background rounded-lg transition-colors"
                    >
                        <LuTrash2 className="h-5 w-5" />
                    </button>
                </div>
            </div>

            {/* Badge Tags: Category & Employee */}
            <div className="flex flex-wrap items-center gap-2">
                {category ? (
                    <span
                        className="inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium"
                        style={{
                            backgroundColor: `${category.color}15`,
                            color: category.color || '#666',
                            border: `1px solid ${category.color}30`
                        }}
                    >
                        {category.icon && <span>{category.icon}</span>}
                        {category.name}
                    </span>
                ) : (
                    <span className="inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium bg-background-alt text-text-muted border border-border-subtle">
                        Sin categoría
                    </span>
                )}

                <span className="inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium bg-background-alt text-text-muted border border-border-subtle">
                    <LuUser className="h-3 w-3" />
                    {employeeName}
                </span>
            </div>

            {/* Extracted Data Key-Values (Simplified) */}
            <div className="pt-2 border-t border-border-subtle grid grid-cols-2 gap-y-2 gap-x-4 text-sm">
                {total && (
                    <div className="col-span-1">
                        <span className="text-xs text-text-muted block">Total</span>
                        <span className="font-semibold text-text">{String(total)}</span>
                    </div>
                )}

                {/* Render visible columns that are not special columns */}
                {row.getVisibleCells().map(cell => {
                    const header = cell.column.columnDef.header;
                    if (typeof header !== 'string') return null;
                    if (['EMPLEADO', 'CATEGORÍA', 'NOMBRE', 'ACCIONES'].includes(header)) return null;

                    // Simple render for mobile
                    return (
                        <div key={cell.id} className="col-span-1 overflow-hidden">
                            <span className="text-xs text-text-muted block uppercase truncate">{header}</span>
                            <span className="text-text truncate block">
                                {flexRender(cell.column.columnDef.cell, cell.getContext())}
                            </span>
                        </div>
                    );
                })}
            </div>
        </div>
    );
}
