"use client"

import dynamic from "next/dynamic"
import { Link } from "@/i18n/navigation"
import { type ColumnDef } from "@tanstack/react-table"
import { ExternalLinkIcon, PencilIcon, Trash2Icon } from "lucide-react"
import { useCallback, useMemo } from "react"
import { useTranslations } from "next-intl"
import { toast } from "sonner"

import { QueryState } from "@/components/api/query-state"
import { MediaPreview } from "@/components/markatty/media-preview"
import { PageHeader } from "@/components/page-header"
import { SuperDataTable } from "@/components/super-data-table"
import { Button } from "@/components/ui/button"
import { useDeleteTheme, useThemeStatistics, useThemes } from "@/hooks/api/use-themes"
import type { ThemeRecord } from "@/lib/admin-content"
import { ApiError } from "@/lib/api/errors"
import type { ThemeStatistics } from "@/lib/api/themes"

const ThemesUsageChart = dynamic(
  () =>
    import("@/components/themes/themes-usage-chart").then((m) => m.ThemesUsageChart),
  { ssr: false }
)

export function ThemesTable({
  initialData,
  initialStatistics,
}: {
  initialData?: ThemeRecord[]
  initialStatistics?: ThemeStatistics
}) {
  const t = useTranslations("Themes")
  const tc = useTranslations("Common")
  const { data = [], isLoading, isError, error } = useThemes(initialData)
  const statsQuery = useThemeStatistics(initialStatistics)
  const deleteThemeMutation = useDeleteTheme()

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

  const handleDelete = useCallback(
    async (theme: ThemeRecord) => {
      if (!window.confirm(t("confirm.delete", { name: theme.name }))) return
      try {
        await deleteThemeMutation.mutateAsync(theme)
        toast.success(t("toast.deleted"))
      } catch (e) {
        showApiError(e)
      }
    },
    [deleteThemeMutation, showApiError, t]
  )

  const columns = useMemo<ColumnDef<ThemeRecord>[]>(
    () => [
      {
        accessorKey: "thumbnailUrl",
        header: t("columns.thumbnail"),
        cell: ({ row }) => (
          <MediaPreview
            src={row.original.thumbnailUrl}
            label={t("columns.thumbnailPreview", { name: row.original.name })}
            className="rounded-md w-20 h-12"
          />
        ),
      },
      { accessorKey: "key", header: t("columns.key") },
      { accessorKey: "name", header: t("columns.name") },
      { accessorKey: "industry", header: t("columns.industry") },
      {
        accessorKey: "previewUrl",
        header: t("columns.previewUrl"),
        cell: ({ row }) => (
          <a
            className="flex items-center gap-2 font-medium text-primary hover:underline underline-offset-4"
            href={row.original.previewUrl}
            rel="noreferrer"
            target="_blank"
          >
            <ExternalLinkIcon className="size-4" />
            {row.original.previewUrl}
          </a>
        ),
      },
      {
        id: "edit",
        header: tc("actions.edit"),
        cell: ({ row }) => (
          <Button variant="ghost" size="icon" className="size-8" asChild>
            <Link
              href={`/themes/${row.original.key}/edit`}
              aria-label={`${tc("actions.edit")} ${row.original.name}`}
            >
              <PencilIcon className="size-4" />
            </Link>
          </Button>
        ),
      },
      {
        id: "delete",
        header: tc("actions.delete"),
        cell: ({ row }) => (
          <Button
            variant="ghost"
            size="icon"
            className="size-8 text-destructive hover:text-destructive"
            aria-label={`${tc("actions.delete")} ${row.original.name}`}
            disabled={deleteThemeMutation.isPending}
            onClick={() => void handleDelete(row.original)}
          >
            <Trash2Icon className="size-4" />
          </Button>
        ),
      },
    ],
    [t, tc, deleteThemeMutation.isPending, handleDelete]
  )

  return (
    <div className="flex flex-col gap-4 md:gap-6 py-4 md:py-6">
      <PageHeader
        title={t("title")}
        actions={
          <Button asChild>
            <Link href="/themes/create">{t("actions.addTheme")}</Link>
          </Button>
        }
      />
      <QueryState
        isLoading={isLoading || statsQuery.isLoading}
        isError={isError || statsQuery.isError}
        error={error ?? statsQuery.error}
      >
        <div className="px-4 lg:px-6">
          <ThemesUsageChart
            data={statsQuery.data?.usage ?? []}
            variant="bar"
            limit={12}
            isLoading={statsQuery.isLoading}
          />
        </div>
        <SuperDataTable
          data={data}
          columns={columns}
          searchKey="name"
          searchPlaceholder={t("placeholders.searchThemes")}
        />
      </QueryState>
    </div>
  )
}
