import { User } from "lucide-react"
import { Button } from "@/components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import apiService from "@/services/apiService"
import { useState } from "react"
import LogoutDialog from "../admin/migrant/Modal/LogoutDialog"
interface HeaderProps {
  title: string
}

export default function Header({ title }: HeaderProps) {
  const [logoutDialogOpen, setLogoutDialogOpen] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const handleLogout = async () => {
    try {
      setIsSubmitting(true)
      await apiService.logout()
      alert("Logged out successfully")
        setTimeout(() => {
          window.location.href = "/login"
        }, 1000) // Delay so the alert shows
      } catch (err) {
        alert("Logout failed. Please try again.")
      } finally {
        setIsSubmitting(false)
        setLogoutDialogOpen(false)
      }
    }


  return (
    
    <header className="h-16 border-b border-gray-800 bg-gray-900 flex items-center justify-between px-6 shadow-lg relative">
      <div className="h-1 bg-gradient-to-r from-[#9B2335] to-[#9B2335]/60 absolute top-0 left-0 w-full"></div>
      <h2 className="text-xl font-medium text-white">{title}</h2>

      <div className="flex items-center space-x-4">

        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="rounded-full text-gray-300 hover:text-white hover:bg-gray-800"
            >
              <User className="size-5" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="bg-gray-800 border-gray-700">
            <DropdownMenuItem className="text-gray-300 hover:text-white hover:bg-gray-700 focus:bg-gray-700 focus:text-white">
              Profile
            </DropdownMenuItem>
            <DropdownMenuItem className="text-gray-300 hover:text-white hover:bg-gray-700 focus:bg-gray-700 focus:text-white">
              Settings
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => setLogoutDialogOpen(true)} className="text-red-400 hover:text-red-300 hover:bg-red-900/20 focus:bg-red-900/20 focus:text-red-300">
              Logout 
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

            <LogoutDialog
              open={logoutDialogOpen}
              onOpenChange={setLogoutDialogOpen}
              onConfirm={handleLogout}
              isSubmitting={isSubmitting}
            />
      </header>
  )
}
