"use client"

import { useSyncExternalStore } from "react"
import { Loader2Icon, RefreshCwIcon } from "lucide-react"
import { useTranslations } from "next-intl"
import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import { useSyncTenants } from "@/hooks/api/use-tenants"
import { ApiError } from "@/lib/api/errors"
import {
  getLastTenantsSyncedAt,
  getServerLastTenantsSyncedAt,
  subscribeLastTenantsSyncedAt,
} from "@/lib/tenants-sync-storage"

export function TenantsSyncControl() {
  const t = useTranslations("Common")
  const syncTenants = useSyncTenants()
  const syncedAt = useSyncExternalStore(
    subscribeLastTenantsSyncedAt,
    getLastTenantsSyncedAt,
    getServerLastTenantsSyncedAt
  )

  function handleRefetch() {
    syncTenants.mutate(undefined, {
      onSuccess: () => {
        toast.success(t("sync.success"))
      },
      onError: (error) => {
        toast.error(
          error instanceof ApiError ? error.message : t("api.errorFallback")
        )
      },
    })
  }

  return (
    <div className="flex flex-wrap items-center gap-3">
      <p className="text-sm text-muted-foreground" suppressHydrationWarning>
        {syncedAt
          ? t("sync.lastSynced", { date: syncedAt })
          : t("sync.neverSynced")}
      </p>
      <Button
        type="button"
        variant="outline"
        disabled={syncTenants.isPending}
        onClick={handleRefetch}
      >
        {syncTenants.isPending ? (
          <Loader2Icon className="animate-spin" data-icon="inline-start" />
        ) : (
          <RefreshCwIcon data-icon="inline-start" />
        )}
        {t("actions.refetch")}
      </Button>
    </div>
  )
}
