import { useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import { Link, usePage } from '@inertiajs/react';
import { CloseButton } from '@/components/ui/CloseButton';
import { cn } from '@/lib/utils';
import type { ClientAreaView } from './content';
import { clientAreaMobileOptions } from './content';
import type { SiteLayoutClientAreaOption } from '@/types';

/*
 * Overlay da Área do cliente: no mobile, painel branco tela cheia (mesmo
 * padrão do hambúrguer — full-width, radius só embaixo). Abas Cliente /
 * Parceiro + cards. No desktop (rodapé) continua card central.
 */

export function ClientAreaModal({ onClose }: { onClose: () => void }) {
    const { siteLayout } = usePage().props;
    const modal = siteLayout.clientAreaModal;
    const [view, setView] = useState<ClientAreaView>('cliente');
    const options = clientAreaMobileOptions(modal, view);

    useEffect(() => {
        const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
        document.addEventListener('keydown', onKey);
        const prev = document.body.style.overflow;
        document.body.style.overflow = 'hidden';
        return () => {
            document.removeEventListener('keydown', onKey);
            document.body.style.overflow = prev;
        };
    }, [onClose]);

    return (
        <div
            className="fixed inset-0 z-[60] web:z-[100] web:flex web:items-center web:justify-center web:p-4"
            role="dialog"
            aria-modal="true"
            aria-labelledby="client-area-title"
        >
            <div
                className="absolute inset-0 bg-white web:bg-gray-800/50"
                onClick={onClose}
                aria-hidden
            />

            <div
                className={cn(
                    'relative z-10 flex max-h-screen w-full flex-col overflow-y-auto rounded-b-[20px] bg-white shadow-navbar',
                    'web:h-auto web:max-h-[90vh] web:max-w-[560px] web:rounded-[20px] web:shadow-subtle',
                )}
            >
                {/* Topo mobile — mesmo espírito do menu principal (logo + fechar) */}
                <div className="flex items-center justify-between px-6 pb-2 pt-4 web:hidden">
                    <Link href="/" aria-label="Omni — página inicial" onClick={onClose} className="shrink-0">
                        {siteLayout.logo ? (
                            <img src={siteLayout.logo} alt="Omni" className="h-9 w-auto" />
                        ) : null}
                    </Link>
                    <CloseButton onClick={onClose} className="size-11 rounded-lg bg-white shadow-menu-button" />
                </div>

                <div className="px-6 pb-10 pt-4 web:p-10">
                    <div className="flex items-start justify-between gap-4">
                        <div className="min-w-0">
                            <p
                                className={cn(
                                    'text-body font-bold',
                                    view === 'parceiro' ? 'text-hero-blue' : 'text-primary',
                                )}
                            >
                                Área do cliente Omni
                            </p>
                            <h2
                                id="client-area-title"
                                className="mt-1 text-heading-sm font-bold text-gray-800"
                            >
                                Selecione uma opção:
                            </h2>
                        </div>
                        <CloseButton onClick={onClose} className="hidden web:flex" />
                    </div>

                    <div
                        className="mt-6 flex border-b border-gray-100"
                        role="tablist"
                        aria-label="Tipo de área"
                    >
                        <TabButton
                            active={view === 'cliente'}
                            tone="cliente"
                            onClick={() => setView('cliente')}
                        >
                            Cliente Omni
                        </TabButton>
                        <TabButton
                            active={view === 'parceiro'}
                            tone="parceiro"
                            onClick={() => setView('parceiro')}
                        >
                            Parceiro Omni
                        </TabButton>
                    </div>

                    <ul className="mt-6 flex flex-col gap-4">
                        {options.map((option) => (
                            <li key={`${view}-${option.title}`}>
                                <OptionCard option={option} onNavigate={onClose} />
                            </li>
                        ))}
                    </ul>
                </div>
            </div>
        </div>
    );
}

function TabButton({
    active,
    tone,
    onClick,
    children,
}: {
    active: boolean;
    tone: ClientAreaView;
    onClick: () => void;
    children: ReactNode;
}) {
    return (
        <button
            type="button"
            role="tab"
            aria-selected={active}
            onClick={onClick}
            className={cn(
                'flex-1 border-b-2 pb-3 text-center text-body font-bold transition-colors',
                active
                    ? tone === 'parceiro'
                        ? 'border-hero-blue text-hero-blue'
                        : 'border-primary text-primary'
                    : 'border-transparent text-gray-500',
            )}
        >
            {children}
        </button>
    );
}

function OptionCard({
    option,
    onNavigate,
}: {
    option: SiteLayoutClientAreaOption;
    onNavigate: () => void;
}) {
    const className =
        'flex items-center gap-4 rounded-xl border border-gray-100 bg-white p-5 text-left shadow-menu-button';

    const inner = (
        <>
            <span className="flex min-w-0 flex-1 flex-col gap-2">
                <span className="flex size-6 items-center justify-center">
                    {option.icon ? (
                        <img src={option.icon} alt="" className="size-6 object-contain" />
                    ) : null}
                </span>
                <span className="text-subtitle font-bold text-gray-800">{option.title}</span>
                <span className="text-body-sm leading-[1.35] text-gray-600">{option.description}</span>
            </span>
            <ChevronRight />
        </>
    );

    if (option.external) {
        return (
            <a
                href={option.href}
                target="_blank"
                rel="noopener noreferrer"
                className={className}
                onClick={onNavigate}
            >
                {inner}
            </a>
        );
    }

    return (
        <Link href={option.href} className={className} onClick={onNavigate}>
            {inner}
        </Link>
    );
}

function ChevronRight() {
    return (
        <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
            aria-hidden
            className="shrink-0 text-gray-400"
        >
            <path
                d="M6 3l5 5-5 5"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
            />
        </svg>
    );
}
