import React, { useEffect, useState } from "react";
import {
  Menu,
  Indicator,
  ActionIcon,
  Text,
  Box,
  Divider,
  ScrollArea,
  Group,
} from "@mantine/core";
import { IconBell, IconClock, IconMessage, IconGitPullRequest, IconCheck } from "@tabler/icons-react";
import { useNavigate } from "react-router";
import moment from "moment";
import { getWorkflowNotifications } from "@/lib/features/workflow/query";
import { markNotificationAsRead } from "@/lib/features/workflow/action";
import type { WorkflowNotification } from "@/lib/features/workflow/types";

export const NotificationsBell: React.FC = () => {
  const navigate = useNavigate();
  const [notifications, setNotifications] = useState<WorkflowNotification[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchNotifications = async () => {
    try {
      const res = await getWorkflowNotifications();
      if (res.success && Array.isArray(res.data)) {
        setNotifications(res.data);
      }
    } catch {
      // silent fail
    }
  };

  useEffect(() => {
    fetchNotifications();
    const interval = setInterval(fetchNotifications, 30000); // poll every 30s
    return () => clearInterval(interval);
  }, []);

  const handleNotificationClick = async (notif: WorkflowNotification) => {
    try {
      await markNotificationAsRead(notif.id);
      fetchNotifications(); // Refresh list

      // Navigate to target entity if metadata is available
      if (notif.entity_type && notif.entity_id) {
        if (notif.entity_type === "MEMBER_OFFER") {
          navigate(`/admin/member-offers/${notif.entity_id}`);
        } else if (notif.entity_type === "RESORT") {
          navigate(`/admin/resorts/${notif.entity_id}`);
        }
      }
    } catch {
      // silent
    }
  };

  const unreadCount = notifications.length;

  const getIconForNotification = (title: string) => {
    const t = title.toLowerCase();
    if (t.includes("comment")) return <IconMessage size={14} style={{ color: "#228be6" }} />;
    if (t.includes("change")) return <IconGitPullRequest size={14} style={{ color: "#fa5252" }} />;
    if (t.includes("resolve")) return <IconCheck size={14} style={{ color: "#40c057" }} />;
    return <IconClock size={14} style={{ color: "#7950f2" }} />;
  };

  return (
    <Menu shadow="md" width={320} position="bottom-end" zIndex={1000}>
      <Menu.Target>
        <Indicator
          color="red"
          size={16}
          label={unreadCount > 0 ? unreadCount : undefined}
          disabled={unreadCount === 0}
          offset={4}
        >
          <ActionIcon
            variant="subtle"
            color="gray"
            radius="xl"
            size="lg"
            onClick={fetchNotifications}
          >
            <IconBell size={20} />
          </ActionIcon>
        </Indicator>
      </Menu.Target>

      <Menu.Dropdown>
        <Box px="sm" py="xs">
          <Group justify="space-between">
            <Text fw={700} size="sm" style={{ fontFamily: "Outfit, Inter, sans-serif" }}>
              Notifications
            </Text>
            {unreadCount > 0 && (
              <Text size="xs" c="dimmed">
                {unreadCount} new
              </Text>
            )}
          </Group>
        </Box>
        <Divider />

        <ScrollArea.Autosize mah={300}>
          {unreadCount === 0 ? (
            <Box py="xl" px="md">
              <Text size="sm" c="dimmed" ta="center">
                All caught up! No unread tasks.
              </Text>
            </Box>
          ) : (
            notifications.map((notif) => (
              <Menu.Item
                key={notif.id}
                onClick={() => handleNotificationClick(notif)}
                style={{ borderBottom: "1px solid #f1f3f5" }}
              >
                <Group align="flex-start" gap="xs" wrap="nowrap">
                  <Box mt={4}>{getIconForNotification(notif.title)}</Box>
                  <Box style={{ flex: 1 }}>
                    <Text size="xs" fw={700}>
                      {notif.title}
                    </Text>
                    <Text size="xs" c="dimmed" style={{ whiteSpace: "normal" }}>
                      {notif.message}
                    </Text>
                    <Text size="10px" c="dimmed" mt={4}>
                      {moment(notif.created_at).fromNow()}
                    </Text>
                  </Box>
                </Group>
              </Menu.Item>
            ))
          )}
        </ScrollArea.Autosize>
      </Menu.Dropdown>
    </Menu>
  );
};
