"use client";

import { useState } from "react";
import { MainHeader } from "@/components/layout/main-header";
import { ProtectedRoute } from "@/components/layout/protected-route";
import { MainFooter } from "@/components/shared/main-footer";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Pagination } from "@/components/ui/pagination";
import { SectionHeader } from "@/components/ui/section-header";
import { useMarkNotificationReadMutation, useNotificationsQuery } from "@/hooks/queries/api-hooks";
import { useLocale } from "@/providers/locale-provider";
import { useToast } from "@/providers/toast-provider";
import { pickLocalizedText } from "@/lib/utils/i18n";
import { getApiErrorMessage } from "@/lib/api/client";

export default function NotificationsPage() {
  const [page, setPage] = useState(1);
  const { locale } = useLocale();
  const { showToast } = useToast();

  const notificationsQuery = useNotificationsQuery({ page, per_page: 20 }, true);
  const markReadMutation = useMarkNotificationReadMutation();

  const meta = notificationsQuery.data?.meta;

  return (
    <div>
      <MainHeader />
      <ProtectedRoute>
        <main className="container-shell section-space space-y-6">
          <SectionHeader
            title="الإشعارات"
            subtitle={`عدد غير المقروء: ${notificationsQuery.data?.unread_count ?? 0}`}
          />

          {notificationsQuery.isLoading ? (
            <Card>
              <p className="text-sm text-slate-500">جارٍ تحميل الإشعارات...</p>
            </Card>
          ) : notificationsQuery.data && notificationsQuery.data.notifications.length > 0 ? (
            <div className="space-y-3">
              {notificationsQuery.data.notifications.map((notification) => (
                <Card key={notification.id} className="space-y-3">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <h3 className="text-base font-extrabold text-slate-900">
                        {pickLocalizedText(notification, "title_ar", "title_en", locale, "إشعار")}
                      </h3>
                      <p className="mt-1 text-sm text-slate-600">
                        {pickLocalizedText(notification, "body_ar", "body_en", locale, "")}
                      </p>
                      <p className="mt-2 text-xs text-slate-400">
                        {notification.sent_at ? new Date(notification.sent_at).toLocaleString(locale === "ar" ? "ar-EG" : "en-US") : "غير محدد"}
                      </p>
                    </div>

                    <div className="flex items-center gap-2">
                      <span className={`rounded-full px-2 py-1 text-xs font-bold ${notification.is_read ? "bg-slate-100 text-slate-600" : "bg-amber-100 text-amber-700"}`}>
                        {notification.is_read ? "مقروء" : "غير مقروء"}
                      </span>
                      {!notification.is_read ? (
                        <Button
                          variant="secondary"
                          onClick={() => {
                            void markReadMutation
                              .mutateAsync(notification.id)
                              .then(() => {
                                showToast({ type: "success", title: "تم تعليم الإشعار كمقروء" });
                              })
                              .catch((error: unknown) => {
                                showToast({ type: "error", title: "فشل تحديث الإشعار", description: getApiErrorMessage(error) });
                              });
                          }}
                        >
                          تعليم كمقروء
                        </Button>
                      ) : null}
                    </div>
                  </div>
                </Card>
              ))}

              {meta ? (
                <Pagination
                  current={meta.current_page}
                  last={meta.last_page}
                  onChange={setPage}
                />
              ) : null}
            </div>
          ) : (
            <EmptyState title="لا توجد إشعارات" description="ستظهر هنا التحديثات المهمة لعروضك المفضلة." />
          )}
        </main>
      </ProtectedRoute>
      <MainFooter />
    </div>
  );
}
