import ClientLayout from '@/Layouts/ClientLayout';
import type { PageProps } from '@/types';
import { Head, usePage } from '@inertiajs/react';
import { CheckCircle2 } from 'lucide-react';
import { useEffect, useState } from 'react';
import ConnectedAccountsSection from './components/ConnectedAccountsSection';
import DangerZoneSection from './components/DangerZoneSection';
import DeleteDialog from './components/DeleteDialog';
import PersonalInfoSection from './components/PersonalInfoSection';
import ProfileSidebar, { type NavSection } from './components/ProfileSidebar';
import SecuritySection from './components/SecuritySection';

type Props = PageProps<{
    mustVerifyEmail: boolean;
    status?: string;
    connectedProvider: string | null;
    hasPassword: boolean;
}>;

export default function ProfileEdit({
    mustVerifyEmail,
    status,
    connectedProvider,
    hasPassword,
}: Props) {
    const { props } = usePage<Props>();
    const user = props.auth.user;
    const flash = props.flash;

    const [showDeleteDialog, setShowDeleteDialog] = useState(false);
    const [activeSection, setActiveSection] = useState('personal');

    useEffect(() => {
        const observer = new IntersectionObserver(
            (entries) => {
                // Pick the topmost intersecting section
                const visible = entries
                    .filter((e) => e.isIntersecting)
                    .sort(
                        (a, b) =>
                            a.boundingClientRect.top - b.boundingClientRect.top,
                    );
                if (visible.length > 0) {
                    setActiveSection(visible[0].target.id);
                }
            },
            { rootMargin: '-15% 0px -60% 0px', threshold: 0 },
        );

        document.querySelectorAll('[data-profile-section]').forEach((el) => {
            observer.observe(el);
        });

        return () => observer.disconnect();
    }, []);

    function scrollTo(id: string) {
        const el = document.getElementById(id);
        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    const emailWarning = mustVerifyEmail && !user.email_verified_at;

    const successMsg =
        flash.success ??
        (status === 'verification-link-sent'
            ? 'Verification email sent. Check your inbox.'
            : null);

    const navSections: NavSection[] = [
        {
            id: 'personal',
            label: 'Personal information',
            badge: emailWarning ? 1 : undefined,
        },
        { id: 'security', label: 'Security' },
        { id: 'connected', label: 'Connected accounts' },
        { id: 'danger', label: 'Danger zone', danger: true },
    ];

    return (
        <ClientLayout title="Profile">
            <Head title="Profile" />

            {/* Two-panel layout */}
            <div className="flex min-h-[calc(100vh-4rem)]">
                <ProfileSidebar
                    user={user}
                    sections={navSections}
                    activeSection={activeSection}
                    onNavigate={scrollTo}
                />

                {/* Main scrollable content */}
                <div className="min-w-0 flex-1">
                    <div className="mx-auto max-w-3xl space-y-5 p-6 lg:p-8">
                        {/* Flash message */}
                        {successMsg && (
                            <div className="flex items-center gap-2 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700 dark:border-emerald-700/30 dark:bg-emerald-900/20 dark:text-emerald-400">
                                <CheckCircle2 className="h-4 w-4 shrink-0" />
                                {successMsg}
                            </div>
                        )}

                        <PersonalInfoSection
                            user={user}
                            emailWarning={emailWarning}
                        />
                        <SecuritySection hasPassword={hasPassword} />
                        <ConnectedAccountsSection
                            connectedProvider={connectedProvider}
                        />
                        <DangerZoneSection
                            onDelete={() => setShowDeleteDialog(true)}
                        />

                        {/* Bottom padding */}
                        <div className="h-8" />
                    </div>
                </div>
            </div>

            {showDeleteDialog && (
                <DeleteDialog
                    hasPassword={hasPassword}
                    onCancel={() => setShowDeleteDialog(false)}
                />
            )}
        </ClientLayout>
    );
}
