import { Form, Link, usePage } from '@inertiajs/react';
import { useState, useRef, useEffect } from 'react';
import { User } from '@/types';

interface HeaderProps {
    onMenuClick: () => void;
    title?: string;
}

interface Announcement {
    id: number;
    title: string;
    message: string;
    type: 'info' | 'warning' | 'success' | 'error';
    created_at: string;
}

export default function Header({ onMenuClick, title }: HeaderProps) {
    const { auth, announcements } = usePage<{ 
        auth: { user: User };
        announcements?: Announcement[] | null;
    }>().props;
    const [isNotificationsOpen, setIsNotificationsOpen] = useState(false);
    const notificationsRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (notificationsRef.current && !notificationsRef.current.contains(event.target as Node)) {
                setIsNotificationsOpen(false);
            }
        };

        if (isNotificationsOpen) {
            document.addEventListener('mousedown', handleClickOutside);
        }

        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [isNotificationsOpen]);

    // Ensure announcements is always an array
    const announcementsArray = Array.isArray(announcements) ? announcements : [];
    const activeAnnouncements = announcementsArray.filter((announcement) => announcement && announcement.id);
    const hasNotifications = activeAnnouncements.length > 0;

    const getTypeColor = (type: string) => {
        switch (type) {
            case 'info':
                return 'bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-200';
            case 'warning':
                return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-200';
            case 'success':
                return 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-200';
            case 'error':
                return 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-200';
            default:
                return 'bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-200';
        }
    };

    return (
        <header className="sticky top-0 z-40 flex h-16 shrink-0 items-center gap-x-4 border-b border-gray-200 bg-white px-4 shadow-sm dark:border-gray-700 dark:bg-gray-800 sm:gap-x-6 sm:px-6 lg:px-8">
            {/* Mobile menu button */}
            <button
                type="button"
                onClick={onMenuClick}
                className="-m-2.5 p-2.5 text-gray-700 lg:hidden dark:text-gray-300"
            >
                <span className="sr-only">Open sidebar</span>
                <Bars3Icon className="h-6 w-6" />
            </button>

            {/* Separator */}
            <div className="h-6 w-px bg-gray-200 lg:hidden dark:bg-gray-700" />

            {/* Page Title */}
            {title && (
                <div className="flex-1 lg:flex-none">
                    <h1 className="text-lg font-semibold text-gray-900 dark:text-white">{title}</h1>
                </div>
            )}

            <div className="flex flex-1 items-center gap-x-4 self-stretch lg:gap-x-6">
                <div className="ml-auto flex items-center gap-x-4 lg:gap-x-6">
                    {/* Coin Balance - Only for user role */}
                    {auth.user.role === 'user' && auth.user.coin_balance !== undefined && (
                        <>
                            <Link
                                href="/topup-coin"
                                className="flex items-center gap-2 rounded-md px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700"
                            >
                                <CoinIcon className="h-5 w-5 text-[#d4af37] dark:text-[#b8941f]" />
                                <span className="hidden sm:inline">
                                    {auth.user.coin_balance?.toLocaleString('id-ID')} {auth.user.coin_abbreviation}
                                </span>
                            </Link>
                            <div className="hidden lg:block lg:h-6 lg:w-px lg:bg-gray-200 dark:lg:bg-gray-700" />
                        </>
                    )}

                    {/* Notifications */}
                    {auth.user.role === 'user' && (
                        <div className="relative" ref={notificationsRef}>
                            <button
                                type="button"
                                onClick={() => setIsNotificationsOpen(!isNotificationsOpen)}
                                className="relative -m-2.5 p-2.5 text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-gray-400"
                            >
                                <span className="sr-only">View notifications</span>
                                <BellIcon className="h-6 w-6" />
                                {hasNotifications && (
                                    <span className="absolute top-0 right-0 flex h-3 w-3">
                                        <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
                                        <span className="relative inline-flex rounded-full h-3 w-3 bg-red-500"></span>
                                    </span>
                                )}
                            </button>

                            {/* Notifications Dropdown */}
                            {isNotificationsOpen && (
                                <div className="absolute right-0 z-50 mt-2 w-80 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none dark:bg-gray-800 dark:ring-gray-700">
                                    <div className="p-4">
                                        <div className="flex items-center justify-between mb-3">
                                            <h3 className="text-sm font-semibold text-gray-900 dark:text-white">
                                                Pengumuman
                                            </h3>
                                            {hasNotifications && (
                                                <span className="inline-flex items-center rounded-full bg-red-100 px-2.5 py-0.5 text-xs font-medium text-red-800 dark:bg-red-900/20 dark:text-red-200">
                                                    {activeAnnouncements.length}
                                                </span>
                                            )}
                                        </div>
                                        <div className="max-h-96 overflow-y-auto space-y-3">
                                            {!hasNotifications ? (
                                                <div className="text-center py-8">
                                                    <BellIcon className="mx-auto h-8 w-8 text-gray-400 dark:text-gray-500" />
                                                    <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
                                                        Tidak ada pengumuman
                                                    </p>
                                                </div>
                                            ) : (
                                                activeAnnouncements.map((announcement) => (
                                                    <div
                                                        key={announcement.id}
                                                        className="rounded-lg border border-gray-200 p-3 dark:border-gray-700"
                                                    >
                                                        <div className="flex items-start justify-between gap-2">
                                                            <div className="flex-1 min-w-0">
                                                                <div className="flex items-center gap-2 mb-1">
                                                                    <span
                                                                        className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${getTypeColor(
                                                                            announcement.type
                                                                        )}`}
                                                                    >
                                                                        {announcement.type}
                                                                    </span>
                                                                </div>
                                                                <h4 className="text-sm font-semibold text-gray-900 dark:text-white truncate">
                                                                    {announcement.title}
                                                                </h4>
                                                                <p className="mt-1 text-xs text-gray-600 dark:text-gray-400 line-clamp-2">
                                                                    {announcement.message}
                                                                </p>
                                                                <p className="mt-1 text-xs text-gray-500 dark:text-gray-500">
                                                                    {new Date(announcement.created_at).toLocaleDateString('id-ID', {
                                                                        year: 'numeric',
                                                                        month: 'short',
                                                                        day: 'numeric',
                                                                    })}
                                                                </p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                ))
                                            )}
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    {/* Separator */}
                    <div className="hidden lg:block lg:h-6 lg:w-px lg:bg-gray-200 dark:lg:bg-gray-700" />

                    {/* Profile dropdown */}
                    <div className="relative">
                        <div className="flex items-center gap-x-4">
                            <div className="hidden lg:block lg:text-right">
                                <p className="text-sm font-semibold leading-6 text-gray-900 dark:text-white">
                                    {auth.user.name}
                                </p>
                                <p className="text-xs leading-5 text-gray-500 dark:text-gray-400">
                                    {auth.user.email}
                                </p>
                            </div>
                            <div className="flex h-8 w-8 items-center justify-center rounded-full bg-[#d4af37] dark:bg-[#b8941f]">
                                <span className="text-sm font-semibold text-white">
                                    {auth.user.name.charAt(0).toUpperCase()}
                                </span>
                            </div>
                        </div>
                    </div>

                    {/* Logout */}
                    <Form action="/logout" method="post" as="button" type="button">
                        <button
                            type="submit"
                            className="rounded-md p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-300"
                        >
                            <span className="sr-only">Logout</span>
                            <ArrowRightOnRectangleIcon className="h-6 w-6" />
                        </button>
                    </Form>
                </div>
            </div>
        </header>
    );
}

// Icons
function Bars3Icon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
        </svg>
    );
}

function BellIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0"
            />
        </svg>
    );
}

function ArrowRightOnRectangleIcon({ className }: { className?: string }) {
    return (
        <svg className={className} 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 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15M12 9l-3 3m0 0l3 3m-3-3h12.75"
            />
        </svg>
    );
}

function CoinIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 6v12m-3-2.818l.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
        </svg>
    );
}

