"use client";

import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { useServerPagination } from "@/presentation/hooks/use-server-pagination";
import { useT, useLocale } from "@/shared/i18n/client";
import { formatDate } from "@/shared/lib/format-date";
import ServerDataTable, {
  type Column,
} from "@/presentation/components/shared/server-data-table";
import { Badge } from "@/presentation/components/ui/badge";
import { Button } from "@/presentation/components/ui/button";
import type { UpsellSignalRow } from "@/domain/entities/entitlement";

const STATUSES = ["open", "handled", "all"] as const;

/**
 * "Signaux commerciaux" (freemium spec 8): the companies that hit a limit of their plan,
 * who to call, and a "handled" mark per signal. A signal tried again after it was handled
 * comes back to the open list.
 */
export function UpsellSignalsTab() {
  const t = useT();
  const locale = useLocale();
  const repo = useRepositories().entitlementRepository;
  const pagination = useServerPagination({ orderBy: "last_seen_at", order: "DESC" });

  const { data: options } = useApiQuery(() => repo.getUpsellSignalOptions(), { deps: [] });
  const { data: response, loading, refetch } = useApiQuery(
    () => repo.findUpsellSignals(pagination.params),
    { deps: [pagination.params] }
  );

  const handleMutation = useApiMutation((id: number) => repo.markUpsellSignalHandled(id), {
    successMessage: t.upsellSignals.toasts.handled,
    onSuccess: () => refetch(),
  });
  const reopenMutation = useApiMutation((id: number) => repo.reopenUpsellSignal(id), {
    successMessage: t.upsellSignals.toasts.reopened,
    onSuccess: () => refetch(),
  });

  const activeStatus = (pagination.filters.status as string) ?? "open";
  const activeKey = pagination.filters.key as string | undefined;
  const busy = handleMutation.loading || reopenMutation.loading;

  const columns: Column<UpsellSignalRow>[] = [
    {
      key: "company",
      label: t.upsellSignals.columns.company,
      render: (row) => (
        <div className="min-w-0">
          <p className="text-sm font-medium truncate">{row.name}</p>
          <p className="text-xs text-muted-foreground truncate">
            {[row.plan, t.upsellSignals.vehicles(row.vehicles)].filter(Boolean).join(" · ")}
          </p>
        </div>
      ),
    },
    {
      key: "contact",
      label: t.upsellSignals.columns.contact,
      render: (row) => (
        <div className="min-w-0">
          <p className="text-sm truncate">{row.owner ?? "—"}</p>
          <p className="text-xs text-muted-foreground truncate">
            {[row.email, row.phone].filter(Boolean).join(" · ") || "—"}
          </p>
        </div>
      ),
    },
    {
      key: "signal",
      label: t.upsellSignals.columns.signal,
      render: (row) => (
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-sm">{row.signal.label}</span>
          {row.signal.handled_at && row.signal.open && (
            <Badge variant="outline">{t.upsellSignals.seenAgain}</Badge>
          )}
        </div>
      ),
    },
    {
      key: "occurrences",
      label: t.upsellSignals.columns.occurrences,
      render: (row) => <span className="text-sm tabular-nums">{row.signal.occurrences}</span>,
    },
    {
      key: "last_seen_at",
      label: t.upsellSignals.columns.lastSeen,
      render: (row) => (
        <span className="text-sm whitespace-nowrap">
          {row.signal.last_seen_at ? formatDate(row.signal.last_seen_at, locale) : "—"}
        </span>
      ),
    },
    {
      key: "follow",
      label: t.upsellSignals.columns.follow,
      render: (row) =>
        row.signal.open ? (
          <Button size="sm" variant="outline" disabled={busy} onClick={() => handleMutation.mutate(row.signal.id)}>
            {t.upsellSignals.markHandled}
          </Button>
        ) : (
          <div className="flex items-center gap-2">
            <span className="text-xs text-muted-foreground">
              {row.signal.handled_by
                ? t.upsellSignals.handledBy(row.signal.handled_by, formatDate(row.signal.handled_at!, locale))
                : t.upsellSignals.handledOn(formatDate(row.signal.handled_at!, locale))}
            </span>
            <Button size="sm" variant="ghost" disabled={busy} onClick={() => reopenMutation.mutate(row.signal.id)}>
              {t.upsellSignals.reopen}
            </Button>
          </div>
        ),
    },
  ];

  return (
    <div className="space-y-4">
      <p className="text-sm text-muted-foreground">{t.upsellSignals.hint}</p>
      <ServerDataTable
        columns={columns}
        data={response?.items ?? []}
        total={response?.total ?? 0}
        page={pagination.page}
        totalPages={response?.last_page ?? 1}
        loading={loading}
        search={pagination.search}
        onSearchChange={pagination.setSearch}
        onPageChange={pagination.setPage}
        onSortChange={pagination.setSort}
        sortBy={pagination.orderBy}
        sortOrder={pagination.order}
        searchPlaceholder={t.upsellSignals.searchPlaceholder}
        emptyMessage={t.upsellSignals.empty}
        // One row per signal: a company with several signals has several rows.
        getRowId={(row) => row.signal.id}
        toolbar={
          <div className="flex items-center gap-2 flex-wrap">
            {STATUSES.map((status) => (
              <Button
                key={status}
                size="sm"
                variant={activeStatus === status ? "default" : "outline"}
                onClick={() => pagination.setFilter("status", status)}
              >
                {t.upsellSignals.status[status]}
              </Button>
            ))}
            <span className="w-px h-6 bg-border mx-1" />
            <Button
              size="sm"
              variant={activeKey ? "outline" : "default"}
              onClick={() => pagination.setFilter("key", undefined)}
            >
              {t.upsellSignals.allKinds}
            </Button>
            {(options?.keys ?? []).map((kind) => (
              <Button
                key={kind.value}
                size="sm"
                variant={activeKey === kind.value ? "default" : "outline"}
                onClick={() => pagination.setFilter("key", activeKey === kind.value ? undefined : kind.value)}
              >
                {kind.label}
              </Button>
            ))}
          </div>
        }
      />
    </div>
  );
}
