"use client";

import { useState } from "react";
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 ConfirmationDialog from "@/presentation/components/shared/confirmation-dialog";
import { Badge } from "@/presentation/components/ui/badge";
import { Button } from "@/presentation/components/ui/button";
import type { DormantAccountRow } from "@/domain/entities/company";

const STATUSES = ["all", "notified", "closed", "restored"] as const;

/**
 * "Comptes dormants" (freemium spec 6.4): the free accounts told they will be closed after a
 * long idle time, the closed ones (users locked out, every piece of data kept) and the
 * restored ones. A closed account is restored here, which gives its users their access back.
 */
export function DormantAccountsTab() {
  const t = useT();
  const locale = useLocale();
  const repo = useRepositories().companyRepository;
  const pagination = useServerPagination({ orderBy: "closed_at", order: "DESC" });
  const [target, setTarget] = useState<DormantAccountRow | null>(null);

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

  const restoreMutation = useApiMutation((companyId: number) => repo.restoreDormantAccount(companyId), {
    successMessage: t.dormantAccounts.toasts.restored,
    onSuccess: () => {
      setTarget(null);
      refetch();
    },
  });

  const activeStatus = (pagination.filters.status as string) ?? "all";
  const date = (value: string | null) => (value ? formatDate(value, locale) : "—");
  const counts = response?.counts;

  const columns: Column<DormantAccountRow>[] = [
    {
      key: "company",
      label: t.dormantAccounts.columns.company,
      render: (row) => (
        <div className="min-w-0">
          <p className="text-sm font-medium truncate">{row.company_name}</p>
          <p className="text-xs text-muted-foreground truncate">
            {[row.owner_name, row.owner_email].filter(Boolean).join(" · ") || "—"}
          </p>
        </div>
      ),
    },
    {
      key: "last_activity_at",
      label: t.dormantAccounts.columns.lastActivity,
      render: (row) => <span className="text-sm whitespace-nowrap">{date(row.last_activity_at)}</span>,
    },
    {
      key: "status",
      label: t.dormantAccounts.columns.status,
      render: (row) => (
        <div className="flex items-center gap-2 flex-wrap">
          <Badge variant={row.status === "closed" ? "destructive" : "outline"}>
            {t.dormantAccounts.badges[row.status]}
          </Badge>
          <span className="text-xs text-muted-foreground">
            {row.status === "notified" && t.dormantAccounts.notified(date(row.notified_at), date(row.close_on))}
            {row.status === "closed" && t.dormantAccounts.closed(date(row.closed_at))}
            {row.status === "restored" && t.dormantAccounts.restored(date(row.restored_at), row.restored_by)}
          </span>
        </div>
      ),
    },
    {
      key: "action",
      label: t.dormantAccounts.columns.action,
      render: (row) =>
        row.status === "closed" ? (
          <Button size="sm" variant="outline" disabled={restoreMutation.loading} onClick={() => setTarget(row)}>
            {t.dormantAccounts.restore}
          </Button>
        ) : null,
    },
  ];

  return (
    <div className="space-y-4">
      <p className="text-sm text-muted-foreground">{t.dormantAccounts.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.dormantAccounts.searchPlaceholder}
        emptyMessage={t.dormantAccounts.empty}
        getRowId={(row) => row.company_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.dormantAccounts.status[status]}
                {status !== "all" && counts ? ` (${counts[status]})` : ""}
              </Button>
            ))}
          </div>
        }
      />

      <ConfirmationDialog
        open={!!target}
        onOpenChange={(open) => !open && setTarget(null)}
        title={t.dormantAccounts.confirm.title}
        description={t.dormantAccounts.confirm.description(target?.company_name)}
        confirmLabel={t.dormantAccounts.restore}
        loading={restoreMutation.loading}
        onConfirm={() => target && restoreMutation.mutate(target.company_id)}
      />
    </div>
  );
}
