import { useState } from 'react';
import type { Link } from './types';
import { postAction } from './api';

const READING_LABELS: Record<string, string> = {
    unread: 'Sin leer',
    reading: 'Leyendo',
    read: 'Leído',
    pending_review: 'Pendiente',
    archived: 'Archivado',
};

const READING_COLORS: Record<string, string> = {
    unread: 'bg-sky-100 text-sky-700 dark:bg-sky-900/30 dark:text-sky-300',
    reading: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300',
    read: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300',
    pending_review: 'bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300',
    archived: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400',
};

interface Props {
    link: Link;
    onRefresh: () => void;
    readUrl: (id: number) => string;
    editUrl: (id: number) => string;
}

export function LinkCard({ link, onRefresh, readUrl, editUrl }: Props) {
    const [favorite, setFavorite] = useState(link.is_favorite);
    const [toggling, setToggling] = useState(false);

    async function toggleFavorite(e: React.MouseEvent) {
        e.preventDefault();
        if (toggling) return;
        setToggling(true);
        setFavorite((f) => !f);
        await postAction(`/enlaces/${link.id}/favorito`);
        setToggling(false);
        onRefresh();
    }

    return (
        <div className="group relative flex flex-col rounded-2xl border border-gray-100 dark:border-white/10 bg-white dark:bg-white/5 shadow-sm hover:shadow-md transition-shadow overflow-hidden">
            {/* Imagen */}
            {link.image_url ? (
                <div className="relative h-36 overflow-hidden bg-gray-100 dark:bg-gray-800 flex-shrink-0">
                    <img
                        src={link.image_url}
                        alt=""
                        className="w-full h-full object-cover"
                        loading="lazy"
                        onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = 'none'; }}
                    />
                    {link.project && (
                        <span
                            className="absolute top-2 left-2 text-xs font-semibold px-2 py-0.5 rounded-full text-white shadow"
                            style={{ backgroundColor: link.project.color }}
                        >
                            <i className={`fa-solid ${link.project.icon} mr-1`} />
                            {link.project.name}
                        </span>
                    )}
                </div>
            ) : (
                <div className="h-2 flex-shrink-0" style={{ backgroundColor: link.project?.color ?? '#38BDF8' }} />
            )}

            {/* Contenido */}
            <div className="flex flex-col flex-1 p-4 gap-2">
                {/* Dominio + tipo */}
                <div className="flex items-center gap-2 text-xs text-gray-400 dark:text-gray-500">
                    {link.favicon_url && (
                        <img src={link.favicon_url} alt="" className="w-4 h-4 rounded-sm" loading="lazy"
                             onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = 'none'; }} />
                    )}
                    <span className="truncate">{link.domain}</span>
                    {link.content_type && (
                        <span className="ml-auto bg-gray-100 dark:bg-gray-700 px-1.5 py-0.5 rounded text-gray-500 dark:text-gray-400 capitalize">
                            {link.content_type}
                        </span>
                    )}
                </div>

                {/* Título */}
                <a
                    href={readUrl(link.id)}
                    className="font-semibold text-gray-900 dark:text-white text-sm leading-snug line-clamp-2 hover:text-primary dark:hover:text-primary-light transition-colors"
                >
                    {link.display_title}
                </a>

                {/* Resumen */}
                {link.summary_short && (
                    <p className="text-xs text-gray-500 dark:text-gray-400 line-clamp-2 leading-relaxed">
                        {link.summary_short}
                    </p>
                )}

                {/* Tags */}
                {link.tags.length > 0 && (
                    <div className="flex flex-wrap gap-1">
                        {link.tags.slice(0, 3).map((tag) => (
                            <span
                                key={tag.id}
                                className="text-xs px-1.5 py-0.5 rounded-full font-medium"
                                style={{ backgroundColor: tag.color + '22', color: tag.color }}
                            >
                                {tag.name}
                            </span>
                        ))}
                        {link.tags.length > 3 && (
                            <span className="text-xs text-gray-400">+{link.tags.length - 3}</span>
                        )}
                    </div>
                )}

                {/* Footer */}
                <div className="mt-auto flex items-center justify-between pt-2 border-t border-gray-100 dark:border-white/5">
                    <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${READING_COLORS[link.reading_status] ?? ''}`}>
                        {READING_LABELS[link.reading_status] ?? link.reading_status}
                    </span>
                    <div className="flex items-center gap-2">
                        <button
                            onClick={toggleFavorite}
                            className={`text-sm transition-colors ${favorite ? 'text-amber-400' : 'text-gray-300 dark:text-gray-600 hover:text-amber-400'}`}
                            aria-label={favorite ? 'Quitar de favoritos' : 'Añadir a favoritos'}
                        >
                            <i className={`fa-${favorite ? 'solid' : 'regular'} fa-star`} />
                        </button>
                        <a
                            href={editUrl(link.id)}
                            className="text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-colors"
                            aria-label="Editar enlace"
                        >
                            <i className="fa-solid fa-pen" />
                        </a>
                        <a
                            href={link.url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-xs text-gray-400 hover:text-primary dark:hover:text-primary-light transition-colors"
                            aria-label="Abrir enlace"
                        >
                            <i className="fa-solid fa-arrow-up-right-from-square" />
                        </a>
                    </div>
                </div>
            </div>
        </div>
    );
}
