"use client"

import { useCallback, useState } from "react"
import {
  BrushCleaningIcon,
  CircleUserRoundIcon,
  KeyRoundIcon,
  OrbitIcon,
  PencilIcon,
  Trash2Icon,
} from "lucide-react"
import { useTranslations } from "next-intl"
import { toast } from "sonner"

import { AssignPlanDialog } from "@/components/assign-plan-dialog"
import type { SuperRowAction } from "@/components/super-data-table"
import { ApiError } from "@/lib/api/errors"
import {
  loginAsTenantAdmin,
  permanentDeleteTenantCatalog,
  resetTenantPassword,
} from "@/lib/api/tenants"

export type TenantActionRow = {
  id: string
}

export function useTenantRowActions(onMutate?: () => void) {
  const t = useTranslations("Tenants")
  const tc = useTranslations("Common")
  const [assignPlanTenantId, setAssignPlanTenantId] = useState<string | null>(null)

  const showApiError = useCallback(
    (e: unknown) => {
      toast.error(e instanceof ApiError ? e.message : tc("api.errorFallback"))
    },
    [tc]
  )

  const actionsForRow = useCallback(
    (row: TenantActionRow): SuperRowAction<TenantActionRow>[] => [
      {
        type: "action",
        label: tc("actions.assignPlan"),
        icon: OrbitIcon,
        onClick: () => setAssignPlanTenantId(row.id),
      },
      {
        type: "link",
        label: tc("actions.edit"),
        icon: PencilIcon,
        href: () => `/tenants/${row.id}/edit`,
      },
      {
        type: "action",
        label: tc("actions.resetPassword"),
        icon: KeyRoundIcon,
        onClick: async () => {
          const password = window.prompt(tc("labels.newPassword"))
          if (!password) {
            toast.message(t("toast.passwordResetCancelled"))
            return
          }
          const confirm = window.prompt(tc("labels.confirmPassword"))
          if (password !== confirm) {
            toast.error(tc("api.errorFallback"))
            return
          }
          try {
            await resetTenantPassword(row.id, password, confirm ?? password)
            toast.success(t("toast.passwordReset"))
          } catch (e) {
            showApiError(e)
          }
        },
      },
      {
        type: "action",
        label: t("actions.loginAsStoreAdmin"),
        icon: CircleUserRoundIcon,
        onClick: async () => {
          try {
            const { url } = await loginAsTenantAdmin(row.id)
            if (url) {
              toast.success(t("toast.loginAsAdminOpened"))
              window.open(url, "_blank", "noopener,noreferrer")
            } else {
              toast.error(t("toast.loginAsAdminNoUrl"))
            }
          } catch (e) {
            showApiError(e)
          }
        },
      },
      { type: "separator" },
      {
        type: "action",
        label: t("actions.clearCash"),
        icon: BrushCleaningIcon,
        onClick: () => {
          toast.message(t("actions.clearCash"))
        },
      },
      {
        type: "action",
        label: tc("actions.permanentDelete"),
        icon: Trash2Icon,
        destructive: true,
        onClick: async () => {
          if (!window.confirm(t("Edit.confirm.deleteCatalog"))) return
          try {
            await permanentDeleteTenantCatalog(row.id)
            toast.success(t("toast.catalogDeleted"))
            onMutate?.()
          } catch (e) {
            showApiError(e)
          }
        },
      },
    ],
    [onMutate, showApiError, t, tc]
  )

  const assignPlanDialog = (
    <AssignPlanDialog
      tenantId={assignPlanTenantId}
      open={assignPlanTenantId !== null}
      onOpenChange={(open) => {
        if (!open) setAssignPlanTenantId(null)
      }}
      onSuccess={() => {
        setAssignPlanTenantId(null)
        onMutate?.()
      }}
    />
  )

  return { actionsForRow, assignPlanDialog }
}
