"use client";

import { useRouter } from "next/navigation";
import { CheckCheck } from "lucide-react";
import { useUrlState } from "@/lib/use-url-state";
import { PageHeader } from "@/components/shared/page-header";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ErrorState, TableSkeleton } from "@/components/shared/states";
import { Pagination } from "@/components/shared/pagination";
import { useCan } from "@/features/auth/use-can";
import {
  useMarkAllNotificationsRead,
  useMarkNotificationRead,
  useNotifications,
} from "@/features/notifications/use-notifications";
import { NotificationItem, NotificationsEmpty } from "@/features/notifications/notification-rows";
import { useT } from "@/i18n";
import type { AdminNotification, AdminNotificationGroupValue } from "@/types/notification";

const NOTIFICATION_GROUPS: ("order" | "vehicle" | "application" | "system")[] = [
  "order",
  "vehicle",
  "application",
  "system",
];

/**
 * The full internal inbox: every notification the back office fired, newest
 * first, filterable by area, with a per-row "open + mark read" and a single
 * "mark everything read" move.
 */
export default function NotificationsPage() {
  const t = useT();
  const router = useRouter();
  const { can } = useCan();
  const [page, setPage] = useUrlState("page", 1, (value) => {
    const parsed = Number.parseInt(value, 10);
    return Number.isFinite(parsed) && parsed >= 1 ? parsed : null;
  });
  const [group, setGroup] = useUrlState<AdminNotificationGroupValue | "">(
    "group",
    "",
    (value) => (NOTIFICATION_GROUPS.includes(value as AdminNotificationGroupValue) ? (value as AdminNotificationGroupValue) : ""),
  );

  const query = useNotifications({ page, rows: 10, group: group || undefined });
  const markRead = useMarkNotificationRead();
  const markAll = useMarkAllNotificationsRead();

  const notifications = query.data?.Model ?? [];
  const totalPages = query.data?.Total ?? 1;
  const records = query.data?.Records ?? 0;

  function openNotification(notification: AdminNotification) {
    if (!notification.is_read && can("notifications.read")) {
      void markRead.mutate(notification.uuid);
    }
    const target = notification.action_url ?? "/notifications";
    void router.push(target);
  }

  return (
    <div>
      <PageHeader
        title={t("notifications.title")}
        subtitle={t("notifications.subtitle")}
        actions={
          can("notifications.read") && records > 0 ? (
            <Button
              variant="outline"
              size="sm"
              onClick={() => void markAll.mutate()}
              disabled={markAll.isPending}
            >
              <CheckCheck className="h-4 w-4" aria-hidden />
              {t("notifications.markAllRead")}
            </Button>
          ) : null
        }
      />

      <Tabs value={group} onValueChange={(value) => setGroup(value as AdminNotificationGroupValue | "")}>
        <TabsList>
          <TabsTrigger value="">{t("common.all")}</TabsTrigger>
          {NOTIFICATION_GROUPS.map((name) => (
            <TabsTrigger key={name} value={name}>
              {t(`notifications.groups.${name}`)}
            </TabsTrigger>
          ))}
        </TabsList>
      </Tabs>

      <div className="mt-4">
        {query.isPending ? (
          <Card className="p-4">
            <TableSkeleton rows={5} cols={1} />
          </Card>
        ) : query.isError ? (
          <Card>
            <ErrorState message={String(query.error)} />
          </Card>
        ) : notifications.length === 0 ? (
          <Card>
            <CardContent>
              <NotificationsEmpty />
            </CardContent>
          </Card>
        ) : (
          <Card>
            <CardContent className="space-y-1 p-2 sm:p-3">
              {notifications.map((notification) => (
                <NotificationItem
                  key={notification.uuid}
                  notification={notification}
                  onOpen={() => openNotification(notification)}
                />
              ))}
            </CardContent>
            <Pagination
              page={page}
              totalPages={totalPages}
              records={records}
              onPageChange={setPage}
            />
          </Card>
        )}
      </div>

      {can("notifications.read") ? null : (
        <p className="mt-4 text-xs text-muted-foreground">{t("notifications.readHint")}</p>
      )}
    </div>
  );
}