"use client";

import { useRouter } from "next/navigation";
import { Nfc, Clock, CheckCircle2, ListChecks, Building2 } from "lucide-react";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useServerPagination } from "@/presentation/hooks/use-server-pagination";
import { useT, useLocale } from "@/shared/i18n/client";
import { formatDate } from "@/shared/lib/format-date";
import { RFID_BATCH_STATUS_COLORS as statusColors } from "@/shared/constants/status-colors";
import ServerDataTable from "@/presentation/components/shared/server-data-table";
import StatsCard from "@/presentation/components/shared/stats-card";
import { Badge } from "@/presentation/components/ui/badge";
import { SearchableSelect } from "@/presentation/components/ui/searchable-select";
import type { RfidCardBatch } from "@/domain/entities/rfid-card-batch";
import type { Column } from "@/presentation/components/shared/server-data-table";

export default function RfidBatchesPage() {
  const t = useT();
  const locale = useLocale();
  usePageHeader(t.pages.rfidBatches.title, t.pages.rfidBatches.subtitle);
  const container = useRepositories();
  const pagination = useServerPagination();
  const router = useRouter();

  const { data: stats } = useApiQuery(
    () => container.rfidCardBatchRepository.getStats(),
    { deps: [] }
  );

  const { data: companies } = useApiQuery(
    () => container.companyRepository.getOptions(),
    { deps: [] }
  );

  const { data: response, loading } = useApiQuery(
    () => container.rfidCardBatchRepository.findAll(pagination.params),
    { deps: [pagination.params] }
  );

  const columns: Column<RfidCardBatch>[] = [
    {
      key: "reference",
      label: t.rfid.columns.reference,
      sortable: true,
      render: (row) => <span className="font-medium text-foreground">{row.reference}</span>,
    },
    {
      key: "company",
      label: t.rfid.columns.company,
      render: (row) => <span className="text-sm">{row.company?.name ?? "—"}</span>,
    },
    {
      key: "status",
      label: t.rfid.columns.status,
      render: (row) => (
        <Badge className={`${statusColors[row.status] ?? ""} border-0 text-xs`}>
          {row.status_label}
        </Badge>
      ),
    },
    {
      key: "changes_count",
      label: t.rfid.columns.changes,
      render: (row) => <span className="text-sm tabular-nums">{row.changes_count}</span>,
    },
    {
      key: "submitted_by",
      label: t.rfid.columns.submittedBy,
      render: (row) => <span className="text-xs">{row.submitted_by ?? "—"}</span>,
    },
    {
      key: "submitted_at",
      label: t.rfid.columns.submittedAt,
      sortable: true,
      render: (row) => (
        <span className="text-xs">
          {row.submitted_at ? formatDate(row.submitted_at, locale) : "—"}
        </span>
      ),
    },
  ];

  return (
    <div className="p-6 space-y-6">
      {stats && (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
          <StatsCard title={t.rfid.stats.total} value={stats.total} icon={Nfc} accent="blue" />
          <StatsCard title={t.rfid.stats.processing} value={stats.processing} icon={Clock} accent="amber" />
          <StatsCard title={t.rfid.stats.processed} value={stats.processed} icon={CheckCircle2} accent="green" />
          <StatsCard title={t.rfid.stats.changesPending} value={stats.changes_pending} icon={ListChecks} accent="purple" />
          <StatsCard title={t.rfid.stats.companies} value={stats.companies} icon={Building2} accent="cyan" />
        </div>
      )}

      <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.rfid.searchPlaceholder}
        emptyMessage={t.rfid.empty}
        onRowClick={(row) => router.push(`/cartes-rfid/${row.id}`)}
        toolbar={
          <>
            <SearchableSelect
              label={t.rfid.filters.status}
              triggerClassName="w-40"
              placeholder={t.rfid.filters.status}
              value={(pagination.filters.status as string) ?? "all"}
              onValueChange={(v) => pagination.setFilter("status", v === "all" ? undefined : v)}
              options={[
                { value: "all", label: t.rfid.filters.allStatuses },
                { value: "processing", label: t.rfid.statuses.processing },
                { value: "processed", label: t.rfid.statuses.processed },
              ]}
            />
            <SearchableSelect
              label={t.rfid.filters.company}
              triggerClassName="w-52"
              placeholder={t.rfid.filters.company}
              value={String(pagination.filters.company_id ?? "all")}
              onValueChange={(v) => pagination.setFilter("company_id", v === "all" ? undefined : Number(v))}
              options={[
                { value: "all", label: t.rfid.filters.allCompanies },
                ...(companies?.map((c) => ({ value: String(c.value), label: c.label })) ?? []),
              ]}
            />
          </>
        }
      />
    </div>
  );
}
