"use client";

import { pushDict } from "@/features/push/dict";
import {
  useEnablePushNotificationsMutation,
  usePushPermissionState,
  usePushSubscriptions,
} from "@/features/push/hooks/use-push-notifications";
import { isPushSupported } from "@/features/push/utils/push-client";

export function PushNotificationsSettings() {
  const permission = usePushPermissionState();
  const { data: subscriptions = [], isLoading } = usePushSubscriptions();
  const enableMutation = useEnablePushNotificationsMutation();

  const isEnabled = permission === "granted" && subscriptions.length > 0;

  if (!isPushSupported()) {
    return (
      <section className="flex flex-col gap-3 rounded-3xl bg-card p-5 shadow-soft-sm sm:p-6">
        <div>
          <h2 className="text-sm font-semibold text-card-foreground">
            {pushDict.title}
          </h2>
          <p className="mt-1 text-sm text-muted-foreground">
            {pushDict.unsupported}
          </p>
        </div>
      </section>
    );
  }

  return (
    <section className="flex flex-col gap-4 rounded-3xl bg-card p-5 shadow-soft-sm sm:p-6">
      <div>
        <h2 className="text-sm font-semibold text-card-foreground">
          {pushDict.title}
        </h2>
        <p className="mt-1 text-sm text-muted-foreground">
          {pushDict.description}
        </p>
      </div>

      {permission === "denied" ? (
        <p className="text-sm text-destructive">{pushDict.denied}</p>
      ) : null}

      {!isEnabled ? (
        <button
          type="button"
          onClick={() => enableMutation.mutate()}
          disabled={
            enableMutation.isPending ||
            permission === "denied" ||
            isLoading
          }
          className="inline-flex h-12 items-center justify-center rounded-2xl bg-primary px-6 text-sm font-semibold text-primary-foreground shadow-soft-sm transition-all hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-70"
        >
          {enableMutation.isPending ? pushDict.enabling : pushDict.enable}
        </button>
      ) : (
        <p className="text-sm font-medium text-primary">{pushDict.enabled}</p>
      )}
    </section>
  );
}
