"use client";

import { useEffect, useState } from "react";
import { toast } from "sonner";
import { ArrowUpDown, Filter, Loader2, PlugZap, ScanSearch } from "lucide-react";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useServerPagination } from "@/presentation/hooks/use-server-pagination";
import { useT } from "@/shared/i18n/client";
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/presentation/components/ui/select";
import type {
  LinkbycarClientEligibility,
  LinkbycarStageFilter,
  LinkbycarStatusFilter,
} from "@/domain/entities/vehicle";

/** 5s x 36 = 3 minutes of watching a company once a bulk test or connection is queued. */
const POLL_INTERVAL_MS = 5000;
const MAX_POLLS = 36;

const STATUSES: LinkbycarStatusFilter[] = ["client", "prospect", "dormant", "former", "test", "all"];
const STAGES: LinkbycarStageFilter[] = ["all", "to_test", "eligible", "connected"];

const STATUS_BADGE_STYLES: Record<"client" | "prospect" | "dormant" | "former" | "test", string> = {
  client: "border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-300",
  prospect: "border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-300",
  dormant: "border-violet-200 bg-violet-50 text-violet-700 dark:border-violet-900 dark:bg-violet-950/40 dark:text-violet-300",
  former: "border-slate-200 bg-slate-100 text-slate-600 dark:border-slate-800 dark:bg-slate-900/40 dark:text-slate-300",
  test: "border-violet-200 bg-violet-50 text-violet-700 dark:border-violet-900 dark:bg-violet-950/40 dark:text-violet-300",
};

/**
 * The companies and where their fleet stands with LinkByCar, by client status (clients first). Per company: a free
 * eligibility test of its vehicles not linked yet, then the connection of the eligible ones (one paid subscription
 * each, confirmed). Both run as queued jobs; the list is re-read while they drain.
 */
export default function TelematicsEligibilityPage() {
  const t = useT();
  const copy = t.telematicsEligibility;
  const { vehicleRepository } = useRepositories();
  const pagination = useServerPagination({ initialFilters: { status: "client", stage: "all", sort: "vehicles" } });
  const [watching, setWatching] = useState<Record<number, number>>({});
  const [confirmTarget, setConfirmTarget] = useState<LinkbycarClientEligibility | null>(null);

  usePageHeader(t.pages.telematicsEligibility.title, t.pages.telematicsEligibility.subtitle);

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

  const isWatching = Object.keys(watching).length > 0;

  useEffect(() => {
    if (!isWatching) return;

    const id = setTimeout(() => {
      setWatching((current) =>
        Object.fromEntries(
          Object.entries(current)
            .map(([companyId, left]) => [companyId, left - 1] as const)
            .filter(([, left]) => left > 0)
        )
      );
      void refetch();
    }, POLL_INTERVAL_MS);

    return () => clearTimeout(id);
  }, [watching, isWatching, refetch]);

  const watch = (companyId: number) => setWatching((current) => ({ ...current, [companyId]: MAX_POLLS }));

  const testMutation = useApiMutation(
    (companyId: number) => vehicleRepository.testCompanyEligibility(companyId).then((result) => ({ companyId, ...result })),
    {
      onSuccess: ({ companyId, queued }) => {
        if (queued === 0) {
          toast.info(copy.toastNothingToTest);
          return;
        }
        toast.success(copy.toastTestQueued(queued));
        watch(companyId);
      },
    }
  );

  const connectMutation = useApiMutation(
    (row: LinkbycarClientEligibility) =>
      vehicleRepository.connectCompanyEligible(row.company.id, row.eligible).then((result) => ({ companyId: row.company.id, ...result })),
    {
      onSuccess: ({ companyId, queued }) => {
        setConfirmTarget(null);
        toast.success(copy.toastConnectQueued(queued));
        watch(companyId);
      },
      onError: () => {
        setConfirmTarget(null);
        void refetch();
      },
    }
  );

  const activeStatus = (pagination.filters.status as LinkbycarStatusFilter) ?? "client";

  const count = (value: number, tone?: "success" | "warning") => (
    <span
      className={
        value === 0
          ? "text-muted-foreground/60"
          : tone === "success"
            ? "font-semibold text-emerald-600"
            : tone === "warning"
              ? "font-semibold text-amber-600"
              : "font-medium"
      }
    >
      {value}
    </span>
  );

  const columns: Column<LinkbycarClientEligibility>[] = [
    {
      key: "company",
      label: copy.columns.company,
      render: (row) => {
        const badge = row.is_test_account ? "test" : row.client_status;
        return (
          <div className="flex min-w-0 items-center gap-2">
            <span className="truncate text-sm font-medium" title={row.company.name}>{row.company.name}</span>
            <span className={`inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold ${STATUS_BADGE_STYLES[badge]}`}>
              {copy.statusBadge[badge]}
            </span>
            {watching[row.company.id] !== undefined && (
              <Badge variant="outline" className="shrink-0 gap-1">
                <Loader2 className="h-3 w-3 animate-spin" />
                {copy.running}
              </Badge>
            )}
          </div>
        );
      },
    },
    { key: "vehicles_total", label: copy.columns.vehicles, render: (row) => count(row.vehicles_total) },
    { key: "without_vin", label: copy.columns.withoutVin, render: (row) => count(row.without_vin) },
    { key: "to_test", label: copy.columns.toTest, render: (row) => count(row.to_test) },
    { key: "eligible", label: copy.columns.eligible, render: (row) => count(row.eligible, "warning") },
    { key: "pending", label: copy.columns.pending, render: (row) => count(row.pending) },
    { key: "connected", label: copy.columns.connected, render: (row) => count(row.connected, "success") },
    {
      key: "actions",
      label: copy.columns.actions,
      render: (row) => (
        <div className="flex items-center justify-end gap-2 whitespace-nowrap">
          <Button
            size="sm"
            variant="outline"
            disabled={row.to_test + row.eligible === 0 || testMutation.loading}
            onClick={() => void testMutation.mutate(row.company.id)}
          >
            <ScanSearch className="mr-1.5 h-3.5 w-3.5" />
            {copy.test}
          </Button>
          {row.eligible > 0 && (
            <Button size="sm" disabled={connectMutation.loading} onClick={() => setConfirmTarget(row)}>
              <PlugZap className="mr-1.5 h-3.5 w-3.5" />
              {copy.connect(row.eligible)}
            </Button>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className="space-y-6 p-6 lg:p-10">
      <p className="text-sm text-muted-foreground">{copy.hint}</p>

      <div className="flex flex-wrap items-center gap-2">
        {STATUSES.map((status) => (
          <Button
            key={status}
            size="sm"
            variant={activeStatus === status ? "default" : "outline"}
            onClick={() => pagination.setFilter("status", status)}
          >
            {copy.status[status]}
            {data?.counts && <span className="ml-1.5 opacity-70">{data.counts[status]}</span>}
          </Button>
        ))}
        <div className="ml-auto flex flex-wrap items-center gap-2">
          <Select
            value={(pagination.filters.stage as string) ?? "all"}
            onValueChange={(value) => pagination.setFilter("stage", value)}
          >
            <SelectTrigger size="sm" className="w-56 gap-2" aria-label={copy.stage.label}>
              <Filter className="h-3.5 w-3.5 text-muted-foreground" />
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {STAGES.map((stage) => (
                <SelectItem key={stage} value={stage}>{copy.stage[stage]}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select
            value={(pagination.filters.sort as string) ?? "vehicles"}
            onValueChange={(value) => pagination.setFilter("sort", value)}
          >
            <SelectTrigger size="sm" className="w-48 gap-2" aria-label={copy.sort.label}>
              <ArrowUpDown className="h-3.5 w-3.5 text-muted-foreground" />
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="vehicles">{copy.sort.vehicles}</SelectItem>
              <SelectItem value="name">{copy.sort.name}</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      <ServerDataTable
        columns={columns}
        data={data?.items ?? []}
        total={data?.total ?? 0}
        page={pagination.page}
        totalPages={data?.last_page ?? 1}
        loading={loading && !data}
        search={pagination.search}
        onSearchChange={pagination.setSearch}
        onPageChange={pagination.setPage}
        searchPlaceholder={copy.searchPlaceholder}
        emptyMessage={copy.empty}
        getRowId={(row) => row.company.id}
      />

      <ConfirmationDialog
        open={!!confirmTarget}
        onOpenChange={(open) => !open && setConfirmTarget(null)}
        title={copy.confirmTitle}
        description={confirmTarget ? copy.confirmDescription(confirmTarget.eligible, confirmTarget.company.name) : ""}
        confirmLabel={confirmTarget ? copy.confirmLabel(confirmTarget.eligible) : undefined}
        loading={connectMutation.loading}
        onConfirm={() => confirmTarget && void connectMutation.mutate(confirmTarget)}
      />
    </div>
  );
}
