import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { cn } from '@/lib/utils';

export type SettingsSection<T extends string> = {
    id: T;
    label: string;
    description: string;
};

export type SettingsSectionsState<T extends string> = {
    /** The open section, or null for the section list on phones. */
    section: T | null;
    /** The section shown on wider screens (the first when none is open). */
    current: T;
    open: (id: T) => void;
    back: () => void;
    /** Show a section without adding history, e.g. one with a failed field. */
    show: (id: T) => void;
    /** Classes for a section's panel: only the current one shows, and none on the phone list. */
    panelClass: (id: T, className?: string) => string;
    /** Classes for parts shown with every section but not on the phone list (e.g. Save). */
    hiddenOnList: string | false;
};

function isPhone(): boolean {
    return window.matchMedia('(max-width: 639px)').matches;
}

/**
 * Settings split into sections: tabs on wider screens, and on phones a list
 * where each section opens as its own page. The open section is kept in the
 * URL hash, so a refresh stays put and the phone's back returns to the list.
 */
export function useSettingsSections<T extends string>(
    sections: readonly SettingsSection<T>[],
): SettingsSectionsState<T> {
    const fromHash = useCallback((): T | null => {
        if (typeof window === 'undefined') {
            return null;
        }

        const hash = window.location.hash.slice(1);

        return sections.find((item) => item.id === hash)?.id ?? null;
    }, [sections]);

    const [section, setSection] = useState<T | null>(fromHash);
    const pushedSection = useRef(false);
    const current = section ?? sections[0].id;

    useEffect(() => {
        const sync = () => setSection(fromHash());
        window.addEventListener('hashchange', sync);

        return () => window.removeEventListener('hashchange', sync);
    }, [fromHash]);

    const show = useCallback((id: T) => {
        window.history.replaceState(null, '', `#${id}`);
        setSection(id);
    }, []);

    const open = (id: T) => {
        if (isPhone() && section === null) {
            pushedSection.current = true;
            window.location.hash = id;
        } else {
            show(id);
        }
    };

    const back = () => {
        if (pushedSection.current) {
            pushedSection.current = false;
            window.history.back();
        } else {
            window.history.replaceState(
                null,
                '',
                window.location.pathname + window.location.search,
            );
            setSection(null);
        }
    };

    return {
        section,
        current,
        open,
        back,
        show,
        panelClass: (id, className) =>
            cn(
                className,
                current !== id && 'hidden',
                section === null && 'max-sm:hidden',
            ),
        hiddenOnList: section === null && 'max-sm:hidden',
    };
}

/**
 * The section list (phones, nothing open), the "All settings" back link
 * (phones, a section open) and the tabs (wider screens).
 */
export function SettingsSectionNav<T extends string>({
    sections,
    state,
    label,
    hasError = () => false,
}: {
    sections: readonly SettingsSection<T>[];
    state: SettingsSectionsState<T>;
    label: string;
    hasError?: (id: T) => boolean;
}) {
    return (
        <>
            {state.section === null ? (
                <nav
                    aria-label={label}
                    className="divide-y divide-surface-200 overflow-hidden rounded-landing-lg border border-surface-200 bg-white sm:hidden"
                >
                    {sections.map((item) => (
                        <button
                            key={item.id}
                            type="button"
                            onClick={() => state.open(item.id)}
                            className="flex w-full items-center gap-3 px-4 py-3.5 text-left hover:bg-surface-100"
                        >
                            <span className="min-w-0 flex-1">
                                <span className="block text-sm font-semibold text-ink">
                                    {item.label}
                                </span>
                                <span
                                    className={cn(
                                        'block text-xs',
                                        hasError(item.id)
                                            ? 'text-red-600'
                                            : 'text-ink-400',
                                    )}
                                >
                                    {hasError(item.id)
                                        ? 'Needs attention'
                                        : item.description}
                                </span>
                            </span>
                            <ChevronRight className="size-4 shrink-0 text-ink-400" />
                        </button>
                    ))}
                </nav>
            ) : (
                <button
                    type="button"
                    onClick={state.back}
                    className="-ml-1 inline-flex items-center gap-1 text-sm font-semibold text-brand sm:hidden"
                >
                    <ChevronLeft className="size-4" />
                    All settings
                </button>
            )}

            <div
                role="tablist"
                aria-label={label}
                className="flex flex-wrap gap-1 rounded-full bg-surface-100 p-1 max-sm:hidden"
            >
                {sections.map((item) => (
                    <button
                        key={item.id}
                        type="button"
                        role="tab"
                        id={`tab-${item.id}`}
                        aria-selected={state.current === item.id}
                        aria-controls={`panel-${item.id}`}
                        onClick={() => state.open(item.id)}
                        className={cn(
                            'flex-1 rounded-full px-3 py-1.5 text-sm font-semibold whitespace-nowrap transition-colors',
                            state.current === item.id
                                ? 'bg-white text-ink shadow-landing-sm'
                                : 'text-ink-500 hover:text-ink',
                            hasError(item.id) && 'text-red-600',
                        )}
                    >
                        {item.label}
                    </button>
                ))}
            </div>
        </>
    );
}

/** Opens the section holding the first field that failed validation. */
export function ShowSectionWithError<T extends string>({
    errors,
    fieldSection,
    show,
}: {
    errors: Record<string, string | undefined>;
    fieldSection: (field: string) => T | undefined;
    show: (id: T) => void;
}) {
    const first = Object.keys(errors)
        .map(fieldSection)
        .find((id) => id !== undefined);

    useEffect(() => {
        if (first) {
            show(first);
        }
    }, [first, show]);

    return null;
}
