"use client";

import { useState } from "react";
import { Link2, Link2Off, Loader2, Search } from "lucide-react";
import { toast } from "sonner";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { useT } from "@/shared/i18n/client";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import type { PennylaneCustomer } from "@/domain/entities/billing";

/**
 * The Pennylane customer a client's invoices go to (billing automation, part 1), linked by
 * hand from the admin: the company the platform knows is not always the entity invoiced.
 * Searched by name or SIREN / SIRET in Pennylane, checked to exist before it is saved.
 */
export function BillingPennylanePanel({ clientId }: { clientId: number }) {
  const t = useT();
  const m = t.billing.manage.pennylane;
  const repo = useRepositories().billingRepository;

  const { data: link, loading, refetch } = useApiQuery(() => repo.getPennylaneLink(clientId), { deps: [clientId] });
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<PennylaneCustomer[] | null>(null);
  const [searching, setSearching] = useState(false);

  const save = useApiMutation(
    (customerId: number | null) => repo.updatePennylaneLink(clientId, customerId),
    {
      onSuccess: (state) => {
        toast.success(state.customer_id ? m.linkedToast : m.unlinkedToast);
        setResults(null);
        refetch();
      },
    }
  );

  const search = async () => {
    if (query.trim().length < 2) return;
    setSearching(true);
    try {
      setResults(await repo.searchPennylaneCustomers(query.trim()));
    } catch (err) {
      const message = (err as { response?: { data?: { message?: string } } }).response?.data?.message;
      toast.error(message || "Une erreur est survenue");
    } finally {
      setSearching(false);
    }
  };

  return (
    <div className="rounded-xl border border-border p-4 space-y-2">
      <p className="flex items-center gap-1.5 font-medium text-sm">
        <Link2 className="w-4 h-4" />
        {m.title}
      </p>
      <p className="text-xs text-muted-foreground">{m.help}</p>

      {loading && !link ? (
        <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
      ) : link && (
        <>
          {!link.enabled && <p className="text-xs text-amber-700 dark:text-amber-300">{m.off}</p>}
          {link.customer_id ? (
            <div className="flex items-center justify-between gap-3 rounded-lg bg-muted/40 px-3 py-2">
              <div className="min-w-0 text-sm">
                <p className="font-medium truncate">
                  {link.customer ? m.linked(link.customer.name ?? "—", link.customer_id) : m.unchecked(link.customer_id)}
                </p>
                {link.customer?.reg_no && <p className="text-xs text-muted-foreground">SIREN / SIRET {link.customer.reg_no}</p>}
              </div>
              <Button size="sm" variant="ghost" className="gap-1.5 text-muted-foreground" disabled={save.loading} onClick={() => save.mutate(null)}>
                <Link2Off className="w-4 h-4" />
                {m.unlink}
              </Button>
            </div>
          ) : (
            <p className="text-xs text-amber-700 dark:text-amber-300">{m.none}</p>
          )}
          {link.siren_differs && link.company_siren && <p className="text-xs text-amber-700 dark:text-amber-300">{m.sirenDiffers(link.company_siren)}</p>}
          {link.also_linked_to.length > 0 && <p className="text-xs text-amber-700 dark:text-amber-300">{m.alsoLinked(link.also_linked_to.join(", "))}</p>}
          {link.error && <p className="text-xs text-red-600">{link.error}</p>}

          {link.enabled && (
            <div className="space-y-2 pt-1">
              <div className="flex gap-2">
                <Input
                  value={query}
                  placeholder={m.search}
                  onChange={(e) => setQuery(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter") search(); }}
                  className="h-8"
                />
                <Button size="sm" variant="outline" className="gap-1.5" disabled={searching || query.trim().length < 2} onClick={search}>
                  {searching ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}
                  {m.searchButton}
                </Button>
              </div>
              {results && results.length === 0 && <p className="text-xs text-muted-foreground">{m.noResult}</p>}
              {results?.map((customer) => (
                <div key={customer.id} className="flex items-center justify-between gap-3 rounded-lg border border-border px-3 py-1.5 text-sm">
                  <div className="min-w-0">
                    <p className="truncate">{customer.name ?? "—"} <span className="text-xs text-muted-foreground">n° {customer.id}</span></p>
                    {customer.reg_no && <p className="text-xs text-muted-foreground">SIREN / SIRET {customer.reg_no}</p>}
                  </div>
                  <Button
                    size="sm"
                    variant="outline"
                    disabled={save.loading || String(customer.id) === link.customer_id}
                    onClick={() => save.mutate(customer.id)}
                  >
                    {m.link}
                  </Button>
                </div>
              ))}
            </div>
          )}
        </>
      )}
    </div>
  );
}
