'use client';

import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { NotificationBell } from '@/components/Ui/NotificationBell';
import { useAuthStore } from '@/lib/auth-store';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import { ProfileService } from '@/lib/profile-service';
import { toReachableAbsoluteUrl } from '@/lib/url-utils';
import { Globe, LayoutDashboard, LogOut, Menu, User } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { Suspense } from 'react';
import { LanguageSwitcher } from './LanguageSwitcher';

interface HeaderProps {
  onToggleSidebar: () => void;
}

function HeaderContent({ onToggleSidebar }: HeaderProps) {
  const { user, token, logout } = useAuthStore();
  const { t, language, setLanguage } = useLanguage();
  const router = useRouter();
  const pathname = usePathname();

  const handleLogout = () => {
    logout();
    router.push('/');
  };

  const handleLanguageChange = async (lang: 'en' | 'es') => {
    setLanguage(lang);
    try {
      await ProfileService.updateProfile({ language: lang });
    } catch {
      // non-critical — language is already updated in localStorage/UI
    }
  };

  const isLoggedIn = !!token;
  const isDashboard = pathname?.includes('/dashboard') || pathname?.includes('/appointments') || pathname?.includes('/patients') || pathname?.includes('/doctors') || pathname?.includes('/profile') || pathname?.includes('/settings') || pathname?.includes('/search') || pathname?.includes('/admin') || pathname?.includes('/subscription');
  const profileImageUrl = user?.profileImage ? toReachableAbsoluteUrl(user.profileImage, API_BASE_URL) : '';

  return (
    <header className="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between sticky top-0 z-50">
      <div className="flex items-center gap-4">
        {isLoggedIn && isDashboard && (
          <Button
            variant="ghost"
            onClick={onToggleSidebar}
            className="md:hidden hover:bg-teal-100 text-gray-600 cursor-pointer hover:text-teal-600 transition-colors group size-12 p-0"
          >
            <Menu className="size-7 group-hover:text-teal-600" />
          </Button>
        )}
        <Link href="/" className="flex items-center gap-2 h-16">
          <div className="w-16 h-16 bg-linear-to-br from-cyan-400 via-cyan-500 to-blue-600 rounded-full flex items-center justify-center overflow-hidden">
            <Image
              src="/assets/logo-v4-fixed.png"
              alt={t('common.clinicLogo')}
              title={t('common.clinicLogo')}
              width={64}
              height={64}
              className="object-cover rounded-full border-4 border-white shadow-lg"
            />
          </div>
          <h1 className="text-xl font-bold text-gray-900">Medklinix</h1>
        </Link>

      </div>

      <div className="flex items-center gap-3">
        <Suspense fallback={null}>
          <LanguageSwitcher />
        </Suspense>

        {isLoggedIn && user ? (
          <>
            <Link href="/dashboard" className="hidden md:block">
              <Button variant="ghost" className="text-gray-600 hover:text-teal-600 hover:bg-teal-100 transition-colors flex items-center gap-2">
                <LayoutDashboard className="h-4 w-4" />
                {t('navigation.dashboard')}
              </Button>
            </Link>

            {/* <Suspense fallback={null}>
              <NotificationBell />
            </Suspense> */}

            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="hover:bg-teal text-gray-600 hover:text-teal-600 transition-colors group gap-3 px-3">
                  <div className="hidden md:flex flex-col items-end text-right">
                    <span className="text-sm font-semibold text-gray-700 group-hover:text-teal-700">{user.firstName} {user.lastName}</span>
                    <span className="text-xs text-gray-500 group-hover:text-teal-600 capitalize">{user.role?.toLowerCase() || user.userType || t('common.user')}</span>
                  </div>
                  {profileImageUrl ? (
                    <img
                      src={profileImageUrl}
                      alt={`${user.firstName} ${user.lastName}`}
                      className="w-9 h-9 rounded-full object-cover border-2 border-teal-600 shadow-sm"
                    />
                  ) : (
                    <div className="w-9 h-9 rounded-full bg-teal-100 border-2 border-teal-200 flex items-center justify-center shadow-sm">
                      <User className="h-5 w-5 text-teal-700" />
                    </div>
                  )}
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className='bg-white min-w-[200px]'>
                <DropdownMenuItem asChild>
                  <Link href="/dashboard" className="md:hidden">
                    <LayoutDashboard className="h-4 w-4 mr-2" />
                    {t('navigation.dashboard')}
                  </Link>
                </DropdownMenuItem>
                <DropdownMenuItem asChild>
                  <Link href="/profile">{t('profile.myProfile')}</Link>
                </DropdownMenuItem>
                <DropdownMenuItem asChild>
                  <Link href="/settings">{t('navigation.settings')}</Link>
                </DropdownMenuItem>

                <DropdownMenuSeparator />

                <DropdownMenuSub>
                  <DropdownMenuSubTrigger>
                    <Globe className="h-4 w-4 mr-2" />
                    <span>{t('common.language')}</span>
                  </DropdownMenuSubTrigger>
                  <DropdownMenuSubContent className="bg-white">
                    <DropdownMenuRadioGroup value={language} onValueChange={(val) => handleLanguageChange(val as 'en' | 'es')}>
                      <DropdownMenuRadioItem value="en">{t('profile.english')}</DropdownMenuRadioItem>
                      <DropdownMenuRadioItem value="es">{t('profile.spanish')}</DropdownMenuRadioItem>
                    </DropdownMenuRadioGroup>
                  </DropdownMenuSubContent>
                </DropdownMenuSub>

                <DropdownMenuSeparator />

                <DropdownMenuItem onClick={handleLogout}>
                  <LogOut className="h-4 w-4 mr-2" />
                  {t('navigation.logout')}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </>
        ) : (
          <>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" className="hover:bg-teal-100 text-gray-600 hover:text-teal-600 transition-colors group md:hidden">
                  <Menu className="h-5 w-5 group-hover:text-teal-600" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className='bg-white'>
                <DropdownMenuItem asChild>
                  <Link href="/login" className="w-full">
                    {t('auth.login')}
                  </Link>
                </DropdownMenuItem>
                <DropdownMenuItem asChild>
                  <Link href="/register" className="w-full">
                    {t('auth.register')}
                  </Link>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>

            <div className="hidden md:flex items-center gap-3">
              <Link href="/login">
                <Button variant="ghost" className="text-gray-600 hover:text-teal-600 hover:bg-teal-100 transition-colors">
                  {t('auth.login')}
                </Button>
              </Link>
              <Link href="/register">
                <Button className="bg-teal-600 hover:bg-teal-700 text-white transition-colors">
                  {t('auth.register')}
                </Button>
              </Link>
            </div>
          </>
        )}
      </div>
    </header>
  );
}

export default function Header(props: HeaderProps) {
  return <HeaderContent {...props} />;
}
