"use client";

import { Landmark, Loader2, Send } 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 { useT, useLocale } from "@/shared/i18n/client";
import { Button } from "@/presentation/components/ui/button";
import type { DirectDebitMandateState } from "@/domain/entities/billing";

const PHASE_STYLE: Record<DirectDebitMandateState["phase"], string> = {
  none: "bg-muted text-muted-foreground",
  waiting: "bg-amber-100 text-amber-800 dark:bg-amber-950/40 dark:text-amber-300",
  active: "bg-emerald-100 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300",
  inactive: "bg-red-100 text-red-700 dark:bg-red-950/40 dark:text-red-300",
};

/**
 * The client's SEPA direct debit mandate on the Pennylane Compte Pro (billing automation,
 * part 3), read back from Pennylane when the "Gérer" dialog opens: its state, who asked
 * for it, Pennylane's last refusal, and the send / send-again action.
 */
export function BillingMandatePanel({ clientId, onChanged }: { clientId: number; onChanged: () => void }) {
  const t = useT();
  const m = t.billing.manage.mandate;
  const locale = useLocale();
  const repo = useRepositories().billingRepository;

  const { data: mandate, loading, refetch } = useApiQuery(() => repo.getMandate(clientId), { deps: [clientId] });

  const send = useApiMutation(() => repo.requestMandate(clientId), {
    successMessage: m.sent,
    onSuccess: () => {
      refetch();
      onChanged();
    },
  });

  /** A YYYY-MM-DD date read as a calendar day, never shifted by the browser's time zone. */
  const day = (ymd: string) => {
    const [year, month, date] = ymd.slice(0, 10).split("-").map(Number);
    return new Date(year, month - 1, date).toLocaleDateString(locale === "fr" ? "fr-FR" : "en-GB", {
      day: "2-digit",
      month: "long",
      year: "numeric",
    });
  };

  return (
    <div className="rounded-xl border border-border p-4 space-y-2">
      <div className="flex items-center justify-between gap-3">
        <p className="flex items-center gap-1.5 font-medium text-sm">
          <Landmark className="w-4 h-4" />
          {m.title}
        </p>
        {mandate && (
          <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${PHASE_STYLE[mandate.phase]}`}>
            {m.phases[mandate.phase]}
          </span>
        )}
      </div>

      {loading && !mandate ? (
        <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
      ) : mandate && (
        <>
          <p className="text-xs text-muted-foreground">
            {!mandate.available
              ? m.off
              : mandate.phase === "active"
                ? mandate.signed_on ? m.active(day(mandate.signed_on)) : m.activeNoDate
                : mandate.phase === "waiting"
                  ? m.waiting(
                      mandate.requested_on ? day(mandate.requested_on) : "—",
                      [m.sources[mandate.request_source ?? ""], mandate.requested_by].filter(Boolean).join(" · ") || "—"
                    )
                  : mandate.phase === "inactive"
                    ? m.inactive(m.statuses[mandate.status ?? ""] ?? mandate.status ?? "—")
                    : m.none}
          </p>
          <p className="text-xs text-muted-foreground">
            {m.email} : <span className="text-foreground">{mandate.email ?? "—"}</span>
          </p>
          {mandate.last_error && (
            <p className="text-xs text-red-600">
              {m.lastError} : {mandate.last_error}
            </p>
          )}
          {mandate.rejects && mandate.rejects.length > 0 && (
            <div className="space-y-1 pt-1">
              <p className="text-xs font-medium">{m.rejects}</p>
              {mandate.rejects.map((reject) => (
                <div key={reject.invoice_id} className="flex items-center justify-between gap-2 text-xs">
                  <span className="text-muted-foreground">
                    {m.reject(
                      reject.number ?? `#${reject.invoice_id}`,
                      reject.amount_ttc.toLocaleString(locale === "fr" ? "fr-FR" : "en-GB", { style: "currency", currency: "EUR" }),
                      day(reject.rejected_on)
                    )}
                    {reject.debit_status ? ` (${m.debitStatuses[reject.debit_status] ?? reject.debit_status})` : ""}
                  </span>
                  <span className={reject.settled ? "text-emerald-700" : "text-red-600 font-medium"}>
                    {reject.settled ? m.settled : m.owed}
                  </span>
                </div>
              ))}
            </div>
          )}
          {mandate.available && mandate.phase !== "active" && (
            <Button
              size="sm"
              variant="outline"
              className="gap-1.5"
              disabled={send.loading}
              onClick={() => send.mutate(undefined)}
            >
              {send.loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
              {mandate.phase === "none" ? m.send : m.resend}
            </Button>
          )}
        </>
      )}
    </div>
  );
}
