"use client";

import { useEffect, useState } from "react";
import { Loader2, Plus } from "lucide-react";
import { toast } from "sonner";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useDebounce } from "@/presentation/hooks/use-debounce";
import { useLocale, useT } from "@/shared/i18n/client";
import { formatDate } from "@/shared/lib/format-date";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import type { IntegrationCompanyOption } from "@/domain/entities/integration";

interface Props {
  integrationId: number;
  /** The sheet's « Statut » switch: the connector is enabled for every client. */
  enabled: boolean;
}

/** One search's answer; `found` is null when the search failed (the error toast said so). */
interface SearchAnswer {
  term: string;
  found: IntegrationCompanyOption[] | null;
}

/**
 * « Clients autorisés » on a connector's sheet: the clients a disabled connector is opened to. Each one sees the
 * connector in myfleet › Connecteurs as if it were enabled for everyone; the list is kept while it is. A line is one
 * company (a subsidiary is added on its own); « Retirer » acts at once, the client's stored connection is kept.
 */
export function IntegrationAllowedCompaniesSection({ integrationId, enabled }: Props) {
  const t = useT();
  const locale = useLocale();
  const container = useRepositories();
  const a = t.pages.integrations.detail.allowedCompanies;
  const errorText = t.pages.integrations.detail.toasts.error;

  const { data: lines, loading, error, refetch } = useApiQuery(
    () => container.integrationRepository.listAllowedCompanies(integrationId),
    { deps: [integrationId] }
  );

  const [query, setQuery] = useState("");
  const [chosen, setChosen] = useState<IntegrationCompanyOption | null>(null);
  const [answer, setAnswer] = useState<SearchAnswer | null>(null);
  const [open, setOpen] = useState(false);
  const [adding, setAdding] = useState(false);
  const [removing, setRemoving] = useState<number | null>(null);

  // The search runs on what is typed, by name or number; a chosen client stops it until the field is typed in again.
  const term = useDebounce(query.trim(), 300);
  const searching = chosen === null && term !== "";

  useEffect(() => {
    if (!searching) return;
    let stale = false;
    container.integrationRepository
      .searchCompaniesToAllow(integrationId, term)
      .then((found) => {
        if (!stale) setAnswer({ term, found });
      })
      .catch(() => {
        if (stale) return;
        setAnswer({ term, found: null });
        toast.error(errorText);
      });
    return () => {
      stale = true;
    };
  }, [container, integrationId, term, searching, errorText]);

  const current = answer?.term === term ? answer : null;
  const showResults = open && chosen === null && query.trim() !== "" && current?.found !== null;

  const choose = (option: IntegrationCompanyOption) => {
    setChosen(option);
    setQuery(a.client(option.name, option.id));
    setOpen(false);
  };

  const handleAdd = async () => {
    if (!chosen) return;
    setAdding(true);
    try {
      await container.integrationRepository.addAllowedCompany(integrationId, chosen.id);
      toast.success(a.toasts.added);
      setQuery("");
      setChosen(null);
      await refetch();
    } catch {
      toast.error(errorText);
    } finally {
      setAdding(false);
    }
  };

  const handleRemove = async (companyId: number) => {
    setRemoving(companyId);
    try {
      await container.integrationRepository.removeAllowedCompany(integrationId, companyId);
      toast.success(a.toasts.removed);
      await refetch();
    } catch {
      toast.error(errorText);
    } finally {
      setRemoving(null);
    }
  };

  return (
    <div className="space-y-2">
      <h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
        {a.title}
      </h4>
      <p className="text-xs text-muted-foreground">
        {enabled ? a.enabledHint : a.disabledHint}
      </p>

      {loading && !lines ? (
        <div className="flex justify-center py-2">
          <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
        </div>
      ) : error && !lines ? (
        <p className="text-xs text-destructive italic pl-1">{errorText}</p>
      ) : lines && lines.length > 0 ? (
        <div className="border border-border/80 rounded-xl overflow-hidden bg-background divide-y divide-border/60">
          {lines.map((line) => (
            <div
              key={line.company_id}
              className="flex items-center justify-between gap-3 p-3.5 text-xs"
            >
              <div className="min-w-0 flex-1">
                <p className="font-semibold text-foreground truncate">
                  {a.client(line.name, line.company_id)}
                </p>
                {line.added_at && (
                  <p className="text-[10px] text-muted-foreground mt-0.5">
                    {a.added(formatDate(line.added_at, locale), line.added_by)}
                  </p>
                )}
              </div>
              <Button
                variant="outline"
                size="sm"
                className="h-7 text-xs shrink-0"
                disabled={removing === line.company_id}
                onClick={() => handleRemove(line.company_id)}
              >
                {removing === line.company_id && (
                  <Loader2 className="w-3.5 h-3.5 animate-spin" />
                )}
                {a.remove}
              </Button>
            </div>
          ))}
        </div>
      ) : (
        <p className="text-xs text-muted-foreground italic pl-1">{a.empty}</p>
      )}

      <div className="flex items-start gap-2">
        <div className="relative flex-1">
          <Input
            value={query}
            placeholder={a.searchPlaceholder}
            className="h-8 text-xs"
            onChange={(e) => {
              setQuery(e.target.value);
              setChosen(null);
              setOpen(true);
            }}
            onFocus={() => setOpen(true)}
            onBlur={() => setOpen(false)}
            onKeyDown={(e) => {
              if (e.key === "Escape") setOpen(false);
            }}
          />
          {showResults && (
            // mousedown kept off the field, so a click on a client lands before the field loses focus.
            <div
              className="absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border border-border bg-popover text-popover-foreground shadow-md py-1"
              onMouseDown={(e) => e.preventDefault()}
            >
              {current === null ? (
                <div className="flex justify-center py-2">
                  <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
                </div>
              ) : current.found && current.found.length > 0 ? (
                current.found.map((option) => (
                  <button
                    key={option.id}
                    type="button"
                    className="block w-full truncate px-3 py-1.5 text-left text-xs hover:bg-accent hover:text-accent-foreground"
                    onClick={() => choose(option)}
                  >
                    {a.client(option.name, option.id)}
                  </button>
                ))
              ) : (
                <p className="px-3 py-1.5 text-xs text-muted-foreground">{a.noResult}</p>
              )}
            </div>
          )}
        </div>
        <Button
          size="sm"
          className="h-8 text-xs"
          disabled={chosen === null || adding}
          onClick={handleAdd}
        >
          {adding ? (
            <Loader2 className="w-3.5 h-3.5 animate-spin" />
          ) : (
            <Plus className="w-3.5 h-3.5" />
          )}
          {a.add}
        </Button>
      </div>
    </div>
  );
}
