'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';

interface User {
    name: string;
    email: string;
    role: string;
}

export default function Layout({ children }: { children: React.ReactNode }) {
    const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
    const [user, setUser] = useState<User | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        // Fetch user info from dashboard API (which includes user data)
        fetch('/api/dashboard', {
            method: 'GET',
            credentials: 'include',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        })
            .then((res) => {
                if (res.ok) {
                    return res.json();
                }
                return null;
            })
            .then((data) => {
                if (data && data.user) {
                    setUser(data.user);
                }
            })
            .catch(() => {
                // Silently fail - user info is optional
            })
            .finally(() => {
                setLoading(false);
            });
    }, []);

    const handleLogout = async () => {
        // #region agent log
        fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'Layout.tsx:46',message:'Logout button clicked',data:{timestamp:Date.now()},sessionId:'debug-session',runId:'run1',hypothesisId:'H4'})}).catch(()=>{});
        // #endregion

        try {
            // Clear any cached user data immediately
            setUser(null);

            const response = await fetch('/api/logout', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
            });

            // #region agent log
            fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'Layout.tsx:55',message:'Logout API response',data:{status:response.status,ok:response.ok},sessionId:'debug-session',runId:'run1',hypothesisId:'H4'})}).catch(()=>{});
            // #endregion

            console.log('Logout response:', { status: response.status, ok: response.ok });

        } catch (error) {
            // #region agent log
            fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'Layout.tsx:62',message:'Logout error',data:{error:error instanceof Error?error.message:'unknown'},sessionId:'debug-session',runId:'run1',hypothesisId:'H4'})}).catch(()=>{});
            // #endregion
            console.error('Logout failed:', error);
        } finally {
            // Redirect to Laravel login page (port 8890) instead of Next.js login (port 3000)
            // The Laravel backend handles authentication at property-app:8890
            window.location.href = 'https://property-app:8890/login';
        }
    };

    const getUserInitials = (name: string) => {
        return name
            .split(' ')
            .map((n) => n[0])
            .join('')
            .toUpperCase()
            .slice(0, 2);
    };

    const getRoleDisplayName = (role: string) => {
        const roleMap: Record<string, string> = {
            manager: 'Manager',
            service_manager: 'Service Manager',
            service_tech: 'Service Tech',
            admin: 'Administrator',
        };
        return roleMap[role] || role;
    };

    return (
        <div className="min-h-screen bg-zinc-50 dark:bg-zinc-900">
            {/* Navigation */}
            <nav className="border-b border-zinc-200 bg-white dark:border-zinc-700 dark:bg-zinc-800">
                <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                    <div className="flex h-16 items-center justify-between">
                        <div className="flex items-center">
                            <Link href="/dashboard" className="flex items-center gap-2 text-xl font-bold text-zinc-900 dark:text-white">
                                <svg className="h-6 w-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                                </svg>
                                Property Portal
                            </Link>
                        </div>

                        {/* Desktop Menu */}
                        <div className="hidden md:flex md:items-center md:gap-4">
                            <Link
                                href="/dashboard"
                                className="text-sm font-medium text-zinc-700 hover:text-zinc-900 dark:text-zinc-300 dark:hover:text-white transition-colors"
                            >
                                Dashboard
                            </Link>

                            {/* User dropdown */}
                            {user && !loading && (
                                <div className="hs-dropdown relative inline-flex [--trigger:hover]">
                                    <button
                                        id="user-menu-button"
                                        type="button"
                                        className="flex items-center gap-3 rounded-full border border-transparent px-3 py-1.5 text-left text-sm font-medium text-zinc-700 transition-colors hover:border-blue-200 hover:bg-blue-50 dark:text-zinc-300 dark:hover:border-blue-500/50 dark:hover:bg-blue-500/10"
                                    >
                                        <div className="flex h-9 w-9 items-center justify-center rounded-full bg-blue-600 text-sm font-semibold text-white">
                                            {getUserInitials(user.name)}
                                        </div>
                                        <div className="hidden text-left lg:block">
                                            <p className="text-sm font-semibold text-zinc-900 dark:text-white">{user.name}</p>
                                            <p className="text-xs text-zinc-500 dark:text-zinc-400">{getRoleDisplayName(user.role)}</p>
                                        </div>
                                        <svg
                                            className="h-4 w-4 text-zinc-500 dark:text-zinc-400"
                                            xmlns="http://www.w3.org/2000/svg"
                                            viewBox="0 0 20 20"
                                            fill="currentColor"
                                            aria-hidden="true"
                                        >
                                            <path
                                                fillRule="evenodd"
                                                d="M5.23 7.21a.75.75 0 011.06.02L10 10.939l3.71-3.71a.75.75 0 111.06 1.061l-4.24 4.24a.75.75 0 01-1.06 0l-4.24-4.24a.75.75 0 01.02-1.06z"
                                                clipRule="evenodd"
                                            />
                                        </svg>
                                    </button>

                                    <div
                                        className="hs-dropdown-menu z-50 mt-2 hidden min-w-[16rem] rounded-xl border border-zinc-100 bg-white p-2 shadow-xl transition-[opacity,margin] duration-200 dark:border-zinc-700 dark:bg-zinc-800"
                                        aria-labelledby="user-menu-button"
                                    >
                                        <div className="rounded-lg bg-zinc-50 px-4 py-3 dark:bg-zinc-900/50">
                                            <p className="text-sm font-semibold text-zinc-900 dark:text-white">{user.name}</p>
                                            <p className="text-xs text-zinc-500 dark:text-zinc-400">{user.email}</p>
                                        </div>
                                        <div className="my-2 border-t border-zinc-100 dark:border-zinc-700" />
                                        <Link
                                            href="/settings/profile"
                                            className="flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-zinc-600 transition-colors hover:bg-zinc-50 hover:text-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-white"
                                        >
                                            <svg
                                                className="h-4 w-4"
                                                xmlns="http://www.w3.org/2000/svg"
                                                fill="none"
                                                viewBox="0 0 24 24"
                                                strokeWidth={1.5}
                                                stroke="currentColor"
                                            >
                                                <path
                                                    strokeLinecap="round"
                                                    strokeLinejoin="round"
                                                    d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.5 20.25a8.25 8.25 0 0115 0"
                                                />
                                            </svg>
                                            Profile
                                        </Link>
                                        <button
                                            onClick={handleLogout}
                                            className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-red-600 transition-colors hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-500/10"
                                        >
                                            <svg
                                                className="h-4 w-4"
                                                xmlns="http://www.w3.org/2000/svg"
                                                fill="none"
                                                viewBox="0 0 24 24"
                                                strokeWidth={1.5}
                                                stroke="currentColor"
                                            >
                                                <path
                                                    strokeLinecap="round"
                                                    strokeLinejoin="round"
                                                    d="M15.75 9V5.25a2.25 2.25 0 00-2.25-2.25h-7.5A2.25 2.25 0 003.75 5.25v13.5A2.25 2.25 0 006 21h7.5a2.25 2.25 0 002.25-2.25V15M12 9l-3 3m0 0l3 3m-3-3h12.75"
                                                />
                                            </svg>
                                            Logout
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Mobile menu button */}
                        <div className="md:hidden">
                            <button
                                onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
                                className="inline-flex items-center justify-center rounded-md p-2 text-zinc-700 hover:bg-zinc-100 hover:text-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-white"
                            >
                                <svg
                                    className="h-6 w-6"
                                    fill="none"
                                    viewBox="0 0 24 24"
                                    stroke="currentColor"
                                >
                                    {mobileMenuOpen ? (
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                    ) : (
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                                    )}
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>

                {/* Mobile menu */}
                {mobileMenuOpen && (
                    <div className="md:hidden border-t border-zinc-200 dark:border-zinc-700">
                        <div className="space-y-1 px-2 pt-2 pb-3">
                            <Link
                                href="/dashboard"
                                className="block rounded-md px-3 py-2 text-base font-medium text-zinc-700 hover:bg-zinc-100 hover:text-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-white"
                                onClick={() => setMobileMenuOpen(false)}
                            >
                                Dashboard
                            </Link>

                            <Link
                                href="/settings/profile"
                                className="block rounded-md px-3 py-2 text-base font-medium text-zinc-700 hover:bg-zinc-100 hover:text-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-white"
                                onClick={() => setMobileMenuOpen(false)}
                            >
                                Profile
                            </Link>

                            {/* Mobile User Info */}
                            {user && !loading && (
                                <div className="border-t border-zinc-200 pt-3 mt-3 dark:border-zinc-700">
                                    <div className="flex items-center gap-3 px-3 py-2">
                                        <div className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-600 text-sm font-semibold text-white">
                                            {getUserInitials(user.name)}
                                        </div>
                                        <div>
                                            <p className="text-sm font-medium text-zinc-900 dark:text-white">{user.name}</p>
                                            <p className="text-xs text-zinc-500 dark:text-zinc-400">{getRoleDisplayName(user.role)}</p>
                                        </div>
                                    </div>
                                </div>
                            )}

                            <button
                                onClick={handleLogout}
                                className="block w-full rounded-md px-3 py-2 text-left text-base font-medium text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-500/10"
                            >
                                Logout
                            </button>
                        </div>
                    </div>
                )}
            </nav>

            {/* Main Content */}
            {children}
        </div>
    );
}
