"use client";

import {
  Box,
  Text,
  Group,
  ActionIcon,
  Menu,
  Avatar,
  UnstyledButton,
} from "@mantine/core";
import {
  IconWorld,
  IconMoon,
  IconSettings,
  IconBell,
  IconSearch,
  IconChevronDown,
} from "@tabler/icons-react";
import { usePathname, useRouter } from "next/navigation";
import theme from "@/styles/theme";
import { useMediaQuery } from "@mantine/hooks";
import { useEffect, useState } from "react";
import Cookies from "js-cookie";

export default function Header() {
  const pathname = usePathname();
  const router = useRouter();
  const isMobile = useMediaQuery("(max-width: 1200px)");

  const [userName, setUserName] = useState("آدمن");

  const getPageTitle = () => {
    const pathMap: { [key: string]: string } = {
      "/dashboard": "لوحة التحكم",
      "/properties": "قائمة السكن",
      "/properties/new": "اضافة سكن جديد",
      "/bookings": "قائمة الحجوزات",
      "/calendar": "عرض التقويم",
      "/reviews": "قائمة التقييمات",
      "/messages": "الرسائل",
      "/finance": "الحسابات",
      "/profile": "الملف الشخصي",
    };

    return pathMap[pathname] || "الرئيسية";
  };

  useEffect(() => {
    try {
      const user = JSON.parse(localStorage.getItem("user") || "{}");
      if (user?.name) {
        setUserName(user.name);
      }
    } catch (e) {
      console.error("Error parsing user data");
    }
  }, []);

  const handleLogout = async () => {
    const token = Cookies.get("auth_token");
    if (!token) return;

    try {
      await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/investors/logout`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      });
    } catch (error) {
      console.error("Logout error:", error);
    } finally {
      Cookies.remove("auth_token");
      localStorage.removeItem("user");
      router.push("/login");
    }
  };

  return (
    <Box
      component="header"
      style={{
        position: isMobile ? "relative" : "fixed",
        width: isMobile ? "100%" : "unset",
        top: 0,
        left: 0,
        right: isMobile ? "unset" : 250,
        height: "100px",
        backgroundColor: "#F8FAFC",
        padding: "0 2rem",
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        zIndex: 100,
      }}
    >
      <Text fw={600} size="lg" c={theme.colors.darkGray}>
        {getPageTitle()}
      </Text>

      <Group gap="md">
        <ActionIcon variant="subtle" color="gray">
          <IconWorld size={20} />
        </ActionIcon>
        <ActionIcon variant="subtle" color="gray">
          <IconMoon size={20} />
        </ActionIcon>
        <ActionIcon variant="subtle" color="gray">
          <IconSettings size={20} />
        </ActionIcon>
        <ActionIcon variant="subtle" color="gray">
          <IconBell size={20} />
        </ActionIcon>
        <ActionIcon variant="subtle" color="gray">
          <IconSearch size={20} />
        </ActionIcon>

        <Menu shadow="md" width={200}>
          <Menu.Target>
            <UnstyledButton>
              <Group gap={7}>
                <Avatar size={30} radius="xl" />
                <Text size="sm" fw={500}>
                  {userName}
                </Text>
                <IconChevronDown size={12} />
              </Group>
            </UnstyledButton>
          </Menu.Target>

          <Menu.Dropdown>
            <Menu.Item onClick={() => router.push("/profile")}>
              الملف الشخصي
            </Menu.Item>
            <Menu.Item>الإعدادات</Menu.Item>
            <Menu.Divider />
            <Menu.Item color="red" onClick={handleLogout}>
              تسجيل الخروج
            </Menu.Item>
          </Menu.Dropdown>
        </Menu>
      </Group>
    </Box>
  );
}
