import { useNavigate } from "@tanstack/react-router";
import { useMutation } from "@tanstack/react-query";
import { LogOut, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { api } from "@/lib/api";
import { authStore, useAuth } from "@/lib/auth";

import { Button } from "@/components/ui/Button";

/**
 * Zone "danger" : déconnexion + suppression de compte (RGPD V2).
 * Le bouton de logout duplique celui du UserMenu — c'est volontaire,
 * c'est un point de sortie attendu dans les paramètres.
 */
export function DangerZone() {
  const { user } = useAuth();
  const navigate = useNavigate();

  const logoutMutation = useMutation({
    mutationFn: () => api.post<void>("/api/v1/account/logout"),
    onSettled: () => {
      authStore.clear();
      toast.success("À très vite.");
      void navigate({ to: "/login" });
    },
  });

  return (
    <div className="flex flex-col gap-5">
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <p className="text-[14px] font-semibold text-ink">
            Se déconnecter de cet appareil
          </p>
          <p className="mt-0.5 text-[12.5px] text-ink-3">
            Connecté en tant que{" "}
            <strong className="text-ink-2">{user?.email}</strong>.
          </p>
        </div>
        <Button
          variant="secondary"
          size="sm"
          loading={logoutMutation.isPending}
          onClick={() => logoutMutation.mutate()}
        >
          <LogOut size={14} aria-hidden="true" /> Se déconnecter
        </Button>
      </div>

      <div className="border-t border-rubis-deep/20" />

      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div className="max-w-md">
          <p className="text-[14px] font-semibold text-ink">
            Supprimer mon compte
          </p>
          <p className="mt-0.5 text-[12.5px] text-ink-3 leading-relaxed">
            Vos factures, plans, clients et historique seront effacés. Action
            irréversible — RGPD article 17.
          </p>
        </div>
        <Button
          variant="danger"
          size="sm"
          disabled
          className="shrink-0"
        >
          <Trash2 size={14} aria-hidden="true" /> Supprimer
          <span className="ml-1 text-[11px] italic opacity-80">(bientôt)</span>
        </Button>
      </div>
    </div>
  );
}
