'use client';

import React from 'react';
import Link from 'next/link';
import { ArrowUpRight, ExternalLink, Link2 } from 'lucide-react';
import { useLocale } from '@/contexts/LocaleContext';
import { useModuleRelatedLinks } from '@/hooks/useModuleRelatedLinks';
import { relatedLinkIcon } from '@/lib/navigation/moduleRelatedLinks';
import type { ModuleRelatedLink, ModuleRelatedSurfaceKey } from '@/lib/navigation/moduleRelatedLinks';
import styles from './ModuleRelatedLinksPanel.module.scss';

export type ModuleRelatedLinksPanelProps = {
    surfaceKey: ModuleRelatedSurfaceKey | string;
    variant: 'inline' | 'footer';
    /** Prefixo para `data-testid` (ex.: `financeiro-movimentos`). */
    pagePrefix: string;
    modalOnClose?: () => void;
    projetoId?: string;
    /**
     * Posição na listagem quando `variant="inline"`.
     * `after` — após a tabela (`ListPageLayout.belowContent`); `before` — entre métricas e listagem (legado).
     */
    listPlacement?: 'before' | 'after';
    /** No desktop mostra só N links e o restante atrás de "Ver mais". No mobile mostra todos. */
    desktopVisibleLimit?: number;
};

function RelatedLinkChip({
    link,
    pagePrefix,
    className,
}: {
    link: ModuleRelatedLink;
    pagePrefix: string;
    className?: string;
}) {
    const secondaryLabel = link.kind === 'config';

    return (
        <Link
            href={link.href}
            className={`${styles.linkChip} ${className ?? ''}`.trim()}
            data-kind={link.kind}
            target={link.external ? '_blank' : undefined}
            rel={link.external ? 'noopener noreferrer' : undefined}
            data-testid={`${pagePrefix}-related-link-${link.key}`}
        >
            <span className={styles.chipIcon} aria-hidden>
                {relatedLinkIcon(link.kind)}
            </span>
            <span
                className={`${styles.chipLabel} ${secondaryLabel ? styles.chipLabelSecondary : ''}`.trim()}
            >
                {link.label}
            </span>
            {link.external ? (
                <ExternalLink size={14} className={styles.chipArrow} aria-hidden />
            ) : (
                <ArrowUpRight size={14} className={styles.chipArrow} aria-hidden />
            )}
        </Link>
    );
}

function RelatedLinksPanelShell({
    links,
    pagePrefix,
    title,
    subtitle,
    testId,
    wrapperClassName,
    desktopVisibleLimit,
}: {
    links: ModuleRelatedLink[];
    pagePrefix: string;
    title: string;
    subtitle?: string;
    testId: string;
    wrapperClassName?: string;
    desktopVisibleLimit?: number;
}) {
    const [expanded, setExpanded] = React.useState(false);
    const limit = desktopVisibleLimit && desktopVisibleLimit > 0 ? desktopVisibleLimit : undefined;
    const temMais = Boolean(limit && links.length > limit);

    return (
        <div
            className={wrapperClassName}
            data-testid={testId}
        >
            <div className={styles.panel}>
                <div className={styles.panelAccent} aria-hidden />
                <div className={styles.header}>
                    <div className={styles.headerIcon} aria-hidden>
                        <Link2 size={18} />
                    </div>
                    <div className={styles.headerText}>
                        <h3 className={styles.title}>{title}</h3>
                        {subtitle ? <p className={styles.subtitle}>{subtitle}</p> : null}
                    </div>
                </div>
                <div className={styles.body}>
                    <nav
                        className={`${styles.linksGrid} ${limit ? styles.linksGridLimit : ''}`.trim()}
                        aria-label={title}
                    >
                        {links.map((link, index) => (
                            <RelatedLinkChip
                                key={link.key}
                                link={link}
                                pagePrefix={pagePrefix}
                                className={
                                    limit && !expanded && index >= limit ? styles.hideOnDesktop : undefined
                                }
                            />
                        ))}
                    </nav>
                    {temMais && !expanded ? (
                        <button
                            type="button"
                            className={styles.verMais}
                            data-testid={`${pagePrefix}-related-ver-mais`}
                            onClick={() => setExpanded(true)}
                        >
                            Ver mais
                        </button>
                    ) : null}
                </div>
            </div>
        </div>
    );
}

function InlineRelatedLinks({
    links,
    pagePrefix,
    title,
    subtitle,
    listPlacement = 'before',
}: {
    links: ModuleRelatedLink[];
    pagePrefix: string;
    title: string;
    subtitle?: string;
    listPlacement?: 'before' | 'after';
}) {
    const wrapperStyle: React.CSSProperties =
        listPlacement === 'after'
            ? { marginTop: 0, marginBottom: 0 }
            : { marginBottom: 12 };

    return (
        <div style={wrapperStyle}>
            <RelatedLinksPanelShell
                links={links}
                pagePrefix={pagePrefix}
                title={title}
                subtitle={listPlacement === 'after' ? subtitle : undefined}
                testId={`${pagePrefix}-related-links-inline`}
            />
        </div>
    );
}

function FooterRelatedLinks({
    links,
    pagePrefix,
    title,
    subtitle,
    desktopVisibleLimit,
}: {
    links: ModuleRelatedLink[];
    pagePrefix: string;
    title: string;
    subtitle?: string;
    desktopVisibleLimit?: number;
}) {
    return (
        <RelatedLinksPanelShell
            links={links}
            pagePrefix={pagePrefix}
            title={title}
            subtitle={subtitle}
            testId={`${pagePrefix}-related-links-footer`}
            wrapperClassName={styles.footerWrap}
            desktopVisibleLimit={desktopVisibleLimit}
        />
    );
}

/**
 * Painel "Relacionado" — variantes inline (listagem) e footer (detalhe).
 * Omitido quando não há links após filtro de permissões.
 */
export function ModuleRelatedLinksPanel({
    surfaceKey,
    variant,
    pagePrefix,
    modalOnClose,
    listPlacement = 'after',
    projetoId,
    desktopVisibleLimit,
}: ModuleRelatedLinksPanelProps) {
    const { t } = useLocale();
    const { links, isEmpty } = useModuleRelatedLinks({
        surfaceKey,
        pagePrefix,
        modalOnClose,
        projetoId,
    });

    if (isEmpty) {
        return null;
    }

    const title = t('navigation.relatedLinks.title');
    const subtitle = t('navigation.relatedLinks.subtitle');

    if (variant === 'footer') {
        return (
            <FooterRelatedLinks
                links={links}
                pagePrefix={pagePrefix}
                title={title}
                subtitle={subtitle}
                desktopVisibleLimit={desktopVisibleLimit}
            />
        );
    }

    return (
        <InlineRelatedLinks
            links={links}
            pagePrefix={pagePrefix}
            title={title}
            subtitle={subtitle}
            listPlacement={listPlacement}
        />
    );
}
