import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "@xtablo/shared";
import { useAuthedApi } from "./auth";

export interface OrganizationSummary {
  id: number;
  name: string;
  plan: string;
  member_count: number;
  tablo_count: number;
}

export interface OrganizationMember {
  id: string;
  email: string | null;
  name: string | null;
  first_name: string | null;
  last_name: string | null;
  avatar_url: string | null;
  created_at: string | null;
  is_temporary: boolean;
  plan: string | null;
}

export interface OrganizationResponse {
  organization: OrganizationSummary;
  members: OrganizationMember[];
  invites_sent: OrganizationInvite[];
  trial_starts_at: string;
  trial_ends_at: string;
  is_trial_expired: boolean;
  required_plan: "solo" | "team";
  required_team_quantity: number;
  active_subscription_plan: "solo" | "team" | "annual" | null;
  active_subscription_quantity: number;
  is_billing_owner: boolean;
}

export interface OrganizationInvite {
  id: number;
  invited_email: string;
  invited_user_id: string | null;
  created_at: string;
  invited_member: {
    id: string;
    email: string | null;
    name: string | null;
    first_name: string | null;
    last_name: string | null;
    avatar_url: string | null;
  } | null;
}

export const useOrganization = () => {
  const api = useAuthedApi();

  return useQuery({
    queryKey: ["organization"],
    queryFn: async () => {
      const { data } = await api.get<OrganizationResponse>("/api/v1/users/organization");
      return data;
    },
  });
};

export const useUpdateOrganization = () => {
  const api = useAuthedApi();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (name: string) => {
      const { data } = await api.patch("/api/v1/users/organization", { name });
      return data;
    },
    onSuccess: () => {
      toast.add({
        title: "Organisation mise à jour",
        description: "Le nom de l'organisation a bien été enregistré",
        type: "success",
      });
      queryClient.invalidateQueries({ queryKey: ["organization"] });
    },
    onError: (error: Error) => {
      toast.add({
        title: "Erreur",
        description: error.message || "Impossible de mettre à jour l'organisation",
        type: "error",
      });
    },
  });
};

export const useInviteOrganizationUser = () => {
  const api = useAuthedApi();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (email: string) => {
      const { data } = await api.post("/api/v1/users/organization/invite", { email });
      return data;
    },
    onSuccess: () => {
      toast.add({
        title: "Invitation envoyée",
        description: "L'utilisateur a été invité dans votre organisation",
        type: "success",
      });
      queryClient.invalidateQueries({ queryKey: ["organization"] });
    },
    onError: (error: Error) => {
      toast.add({
        title: "Erreur",
        description: error.message || "Impossible d'envoyer l'invitation",
        type: "error",
      });
    },
  });
};

export const useRemoveOrganizationMember = () => {
  const api = useAuthedApi();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (memberId: string) => {
      const { data } = await api.delete(`/api/v1/users/organization/members/${memberId}`);
      return data;
    },
    onSuccess: () => {
      toast.add({
        title: "Membre retiré",
        description: "Le membre a été retiré de votre organisation",
        type: "success",
      });
      queryClient.invalidateQueries({ queryKey: ["organization"] });
    },
    onError: (error: Error) => {
      toast.add({
        title: "Erreur",
        description: error.message || "Impossible de retirer ce membre",
        type: "error",
      });
    },
  });
};
