"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Button, Divider, Tabs, Tab } from "@heroui/react";
import {
  Bell,
  BellOff,
  CheckCircle,
  AlertTriangle,
  Info,
  XCircle,
  Trash2,
  Check,
  MoreVertical,
} from "lucide-react";
import { useTranslations } from "next-intl";
import { useLocale } from "next-intl";
import {
  fetchNotifications,
  markNotificationsAsRead,
  deleteNotifications,
} from "@/lib/api";
import { buildNotificationHref } from "@/lib/notificationHref";
import type { Notification } from "@/types/api/notifications.types";
import { useSession } from "@/auth/session-provider";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import AtayaLoader from "@/components/loaders/AtayaLoader";

export default function NotificationsSection() {
  const t = useTranslations("DASHBOARD.NOTIFICATIONS");
  const lang = useLocale();
  const pathname = usePathname();
  const requestLang = (() => {
    const seg = String(pathname || "").split("/")[1] || "";
    const v = seg.toLowerCase();
    if (v === "ar" || v.startsWith("ar")) return "ar";
    if (v === "en" || v.startsWith("en")) return "en";
    const fallback = String(lang || "").toLowerCase();
    return fallback.startsWith("ar") ? "ar" : "en";
  })();
  const isRtl = (requestLang || "").toLowerCase().startsWith("ar");
  const session = useSession();
  const token = session?.access_token;
  const [filter, setFilter] = useState("all");
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedNotifications, setSelectedNotifications] = useState<string[]>(
    [],
  );

  useEffect(() => {
    if (!token) {
      setLoading(false);
      setError(null);
      setNotifications([]);
      return;
    }

    loadNotifications();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token, requestLang]);

  const loadNotifications = async () => {
    try {
      if (!token) return;
      setLoading(true);
      setError(null);
      const response = await fetchNotifications(100, token, requestLang);
      setNotifications(response.data.data);
    } catch (err) {
      setError(
        err instanceof Error ? err.message : "Failed to load notifications",
      );
    } finally {
      setLoading(false);
    }
  };

  const getNotificationIcon = (title: string) => {
    const lowerTitle = title.toLowerCase();
    if (lowerTitle.includes("accepted") || lowerTitle.includes("approved")) {
      return <CheckCircle className="text-green-600" size={20} />;
    } else if (
      lowerTitle.includes("rejected") ||
      lowerTitle.includes("error")
    ) {
      return <XCircle className="text-red-600" size={20} />;
    } else if (lowerTitle.includes("warning") || lowerTitle.includes("soon")) {
      return <AlertTriangle className="text-amber-600" size={20} />;
    } else {
      return <Info className="text-blue-600" size={20} />;
    }
  };

  const getNotificationType = (title: string): string => {
    const lowerTitle = title.toLowerCase();
    if (lowerTitle.includes("accepted") || lowerTitle.includes("approved")) {
      return "success";
    } else if (
      lowerTitle.includes("rejected") ||
      lowerTitle.includes("error")
    ) {
      return "error";
    } else if (lowerTitle.includes("warning") || lowerTitle.includes("soon")) {
      return "warning";
    } else {
      return "info";
    }
  };

  const formatTimeAgo = (readAt: string | null) => {
    if (readAt) {
      return t("read");
    }
    return t("unread");
  };

  const handleMarkAsRead = async (notificationIds: string[]) => {
    try {
      await markNotificationsAsRead(notificationIds, token, requestLang);
      setNotifications((prev) =>
        prev.map((n) =>
          notificationIds.includes(n.id)
            ? { ...n, read_at: new Date().toISOString() }
            : n,
        ),
      );
      setSelectedNotifications([]);
    } catch (err) {
      console.error("Failed to mark as read:", err);
    }
  };

  const handleDelete = async (notificationIds: string[]) => {
    try {
      await deleteNotifications(notificationIds, token, requestLang);
      setNotifications((prev) =>
        prev.filter((n) => !notificationIds.includes(n.id)),
      );
      setSelectedNotifications([]);
    } catch (err) {
      console.error("Failed to delete:", err);
    }
  };

  const toggleSelection = (notificationId: string) => {
    setSelectedNotifications((prev) =>
      prev.includes(notificationId)
        ? prev.filter((id) => id !== notificationId)
        : [...prev, notificationId],
    );
  };

  const toggleAllSelection = () => {
    const filtered =
      filter === "all"
        ? notifications
        : notifications.filter((n) => getNotificationType(n.title) === filter);

    const allSelected = filtered.every((n) =>
      selectedNotifications.includes(n.id),
    );
    if (allSelected) {
      setSelectedNotifications((prev) =>
        prev.filter((id) => !filtered.some((n) => n.id === id)),
      );
    } else {
      setSelectedNotifications((prev) => [
        ...prev,
        ...filtered.filter((n) => !prev.includes(n.id)).map((n) => n.id),
      ]);
    }
  };

  const filtered =
    filter === "all"
      ? notifications
      : notifications.filter((n) => getNotificationType(n.title) === filter);

  const hasUnread = notifications.some((n) => n.read_at === null);
  const filteredIds = filtered.map((n) => n.id);
  const allFilteredSelected =
    filtered.length > 0 &&
    filteredIds.every((id) => selectedNotifications.includes(id));
  const hasSelectedInFilter = filtered.some((n) =>
    selectedNotifications.includes(n.id),
  );

  return (
    <div className="space-y-6">
      <div className="flex flex-col items-start gap-2 pb-2 border-b border-gray-100">
        <div className="flex items-center gap-2">
          <Bell className="text-primary" size={22} />
          <h2 className="text-2xl font-extrabold text-green-800">
            {t("title")}
          </h2>
        </div>
        <p className="text-slate-500 text-sm">{t("subtitle")}</p>
      </div>

      <div className="space-y-6">
        <Tabs
          aria-label={t("tabs_label")}
          selectedKey={filter}
          isVertical={false}
          onSelectionChange={(key) => setFilter(key.toString())}
          color="primary"
          className="pt-2 text-start"
          classNames={{
            tabList: "gap-2 text-start",
            tabWrapper: "w-full justify-start flex flex-col",
            tab: "rounded-lg px-3 py-1 text-sm font-medium data-[selected=true]:bg-primary/10 data-[selected=true]:text-primary",
          }}
        >
          <Tab key="all" title={t("tab_all")} />
          <Tab key="success" title={t("tab_success")} />
          <Tab key="warning" title={t("tab_warning")} />
          <Tab key="info" title={t("tab_info")} />
          <Tab key="error" title={t("tab_error")} />
        </Tabs>

        <div className="space-y-4">
          {loading ? (
            <AtayaLoader />
          ) : error ? (
            <div className="p-6 text-center border rounded-xl text-red-600 text-sm">
              {error}
              <Button
                size="sm"
                variant="flat"
                color="primary"
                onPress={loadNotifications}
                className={isRtl ? "mr-2" : "ml-2"}
              >
                {t("retry")}
              </Button>
            </div>
          ) : filtered.length === 0 ? (
            <div className="p-8 border rounded-xl bg-slate-50/40">
              <div className="mx-auto max-w-md text-center">
                <div className="mx-auto w-14 h-14 rounded-2xl bg-primary/10 flex items-center justify-center">
                  <BellOff className="text-primary" size={26} />
                </div>
                <h3 className="mt-4 text-lg font-extrabold text-slate-800">
                  {t("empty_title")}
                </h3>
                <p className="mt-1 text-sm text-slate-500">
                  {t("empty_description")}
                </p>
                <div className="mt-4 flex items-center justify-center">
                  <Button
                    size="sm"
                    variant="flat"
                    color="primary"
                    onPress={loadNotifications}
                  >
                    {t("empty_refresh")}
                  </Button>
                </div>
              </div>
            </div>
          ) : (
            <>
              {filtered.length > 0 && (
                <div className="flex items-center justify-between p-2 bg-gray-50 rounded-lg">
                  <div className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={allFilteredSelected}
                      onChange={toggleAllSelection}
                      className="rounded"
                    />
                    <span className="text-sm text-gray-600">
                      {t("select_all")} ({filtered.length})
                    </span>
                  </div>
                  {hasSelectedInFilter && (
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        variant="flat"
                        color="primary"
                        startContent={<Check size={16} />}
                        onPress={() =>
                          handleMarkAsRead(
                            filtered
                              .filter(
                                (n) =>
                                  selectedNotifications.includes(n.id) &&
                                  n.read_at === null,
                              )
                              .map((n) => n.id),
                          )
                        }
                      >
                        {t("mark_read")}
                      </Button>
                      <Button
                        size="sm"
                        variant="flat"
                        color="danger"
                        startContent={<Trash2 size={16} />}
                        onPress={() =>
                          handleDelete(
                            filtered
                              .filter((n) =>
                                selectedNotifications.includes(n.id),
                              )
                              .map((n) => n.id),
                          )
                        }
                      >
                        {t("delete_selected")}
                      </Button>
                    </div>
                  )}
                </div>
              )}
              {filtered.map((n) => {
                const type = getNotificationType(n.title);
                const isSelected = selectedNotifications.includes(n.id);
                const isUnread = n.read_at === null;
                const href = buildNotificationHref(n, requestLang);

                return (
                  <div
                    key={n.id}
                    className={`border-l-4 transition hover:shadow-sm rounded-lg border ${
                      type === "success"
                        ? "border-l-green-600"
                        : type === "warning"
                          ? "border-l-amber-500"
                          : type === "error"
                            ? "border-l-red-600"
                            : "border-l-blue-500"
                    } ${isUnread ? "bg-blue-50/50" : "bg-white"} ${
                      isSelected ? "ring-2 ring-primary/20" : ""
                    }`}
                  >
                    <div className="flex justify-between items-center p-3">
                      <div className="flex items-center gap-3">
                        <input
                          type="checkbox"
                          checked={isSelected}
                          onChange={() => toggleSelection(n.id)}
                          className="rounded"
                        />
                        {getNotificationIcon(n.title)}
                        <div className="flex-1">
                          {href ? (
                            <Link
                              href={href}
                              className={`font-bold text-slate-800 hover:underline ${isUnread ? "font-semibold" : ""}`}
                            >
                              {n.title}
                            </Link>
                          ) : (
                            <h3
                              className={`font-bold text-slate-800 ${isUnread ? "font-semibold" : ""}`}
                            >
                              {n.title}
                            </h3>
                          )}
                          <span className="text-xs text-slate-500">
                            {formatTimeAgo(n.read_at)}
                          </span>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {isUnread && (
                          <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
                        )}
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button size="sm" variant="light" isIconOnly>
                              <MoreVertical size={16} />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent>
                            <DropdownMenuItem
                              onSelect={() => {
                                if (n.read_at === null) {
                                  handleMarkAsRead([n.id]);
                                }
                              }}
                            >
                              {t("mark_read")}
                            </DropdownMenuItem>
                            <DropdownMenuSeparator />
                            <DropdownMenuItem
                              onSelect={() => handleDelete([n.id])}
                              className="text-red-600"
                            >
                              {t("delete_selected")}
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </div>
                    </div>
                    <Divider />
                    <div className="p-3">
                      {href ? (
                        <Link
                          href={href}
                          className="block text-sm text-slate-600 text-start hover:underline"
                        >
                          {n.body}
                        </Link>
                      ) : (
                        <p className="text-sm text-slate-600 text-start">
                          {n.body}
                        </p>
                      )}
                    </div>
                  </div>
                );
              })}
            </>
          )}
        </div>

        {filtered.length > 0 && !loading && !error && (
          <div className="pt-2 flex justify-center gap-2">
            {hasUnread && (
              <Button
                variant="flat"
                color="primary"
                size="sm"
                onPress={() =>
                  handleMarkAsRead(
                    notifications
                      .filter((n) => n.read_at === null)
                      .map((n) => n.id),
                  )
                }
              >
                {t("mark_all_read")}
              </Button>
            )}
            <Button
              variant="flat"
              color="danger"
              size="sm"
              onPress={() => {
                if (confirm(t("clear_all_confirm"))) {
                  handleDelete(notifications.map((n) => n.id));
                }
              }}
            >
              {t("clear_all")}
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
