"use client";

import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import { updateVolunteerRegistration } from "@/features/opportunities/services/registrations";
import { getApiErrorMessages } from "@/lib/api/errors";
import { getRolesOfOpportunity } from "@/features/opportunities/services/roles";
import { useLanguageStore } from "@/store/languageStore";
import { Role, SelectOption } from "../components/volunteerListHelpers";
import { usePageCursor, usePagedItems } from "@/features/shared/pagedList";

interface UseTeamsAndRolesArgs {
  opportunityId: string | undefined;
  /** Called after a registration's role is successfully changed. */
  onUpdated: () => void | Promise<void>;
  canManage: boolean;
}

/**
 * The role dropdown (and its menu's own pagination), plus the registration
 * PATCH that assigns a row to one.
 *
 * Teams are gone — the client dropped them from this screen entirely and roles
 * are the only grouping now. The hook kept its name because it is imported
 * under it, but it no longer fetches `/teams/`: that request ran on every load
 * of the volunteers list and nothing consumed its result. The `"team" | "role"`
 * union on `handleUpdate` survives because the API still accepts `team` on the
 * same PATCH and the mobile app and admin dashboard may still send it — we just
 * never do.
 */
export function useTeamsAndRoles({ opportunityId, onUpdated, canManage }: UseTeamsAndRolesArgs) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);

  const queryClient = useQueryClient();
  const [updating, setUpdating] = useState<"team" | "role">("role");
  const [updatingId, setUpdatingId] = useState<string | null>(null);

  const updateRegistrationMutation = useMutation({
    mutationFn: updateVolunteerRegistration,
  });

  /*
   * The dropdown's own pagination, through the shared accumulator rather than
   * a `rolesList` mirror plus an append effect. See `features/shared/pagedList`
   * — the reducer keys on response *identity*, which is what makes
   * `rolesRefetch` below work without clearing the list by hand.
   */
  const { page: rolePage, nextPage, resetPage } = usePageCursor(
    opportunityId ?? ""
  );

  const rolesQuery = useQuery({
    queryKey: ["opportunity-roles", opportunityId, rolePage],
    queryFn: () =>
      getRolesOfOpportunity({
        opportunity_id: opportunityId,
        page: rolePage,
        limit: 10,
      }),
    enabled: Boolean(opportunityId),
  });

  const rolesData = rolesQuery.data;
  const rolesLoading = rolesQuery.isLoading;

  const { items: rolesList } = usePagedItems<Role>({
    resetSignature: opportunityId ?? "",
    response: rolesData,
    isFetching: rolesQuery.isFetching,
    limit: 10,
    dedupeById: true,
  });

  const handleRoleMenuScroll = () => {
    if (
      !rolesLoading &&
      (rolesData?.meta?.pagination?.total_pages ?? 0) > rolePage
    ) {
      nextPage();
    }
  };

  /*
   * Called after a role is created, edited or deleted in the dialog.
   *
   * It no longer clears the accumulated rows by hand: going back to page 1 and
   * invalidating every page of this opportunity's roles makes the next page-1
   * response a new object, and the reducer replaces the list on a new page 1.
   * Invalidating (rather than `rolesQuery.refetch()`) matters because that
   * query object is bound to whichever page was current when it was read — on
   * page 2 the old code refetched page 2 and then showed it as page 1's rows.
   */
  const rolesRefetch = async () => {
    resetPage();
    await queryClient.invalidateQueries({
      queryKey: ["opportunity-roles", opportunityId],
    });
  };

  const roleOptions: SelectOption[] = [
    { label: t("COMMON.NOT_SELECTED"), value: "" },
    ...rolesList.map((role) => ({
      label: String(role[`role_name_${selectedLanguage}`] ?? ""),
      value: String(role.id),
    })),
  ];

  const handleUpdate = async (
    id: string,
    type: "team" | "role",
    value: string | undefined
  ) => {
    if (!canManage) return;
    // The API cannot clear a role (`! empty($data['role'])` leaves it as is),
    // so «غير محدد» would report success while nothing changed (S-VOL-3).
    if (!value) return;
    try {
      setUpdatingId(id);
      setUpdating(type);
      await updateRegistrationMutation.mutateAsync({
        registration: id,
        [type]: value,
      });
      await onUpdated();
      toast.success(t("COMMON.UPDATE_SUCCESS"));
    } catch (error: unknown) {
      // BE-67.5 returns the role-capacity refusal as a 422 with a `role` field
      // error under `response_status.validation_errors`. Reading
      // `data.errors[field][lang]` — the older envelope — missed it entirely and
      // failed silently, so the organizer saw the dropdown snap back with no
      // explanation. `getApiErrorMessages` reads both shapes and the backend
      // has already localized the text from the language header.
      const messages = getApiErrorMessages(error, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(t("COMMON.UPDATE_FAILED"));
      }
    } finally {
      setUpdatingId(null);
    }
  };

  return {
    rolesList,
    roleOptions,
    rolesLoading,
    updating,
    updatingId,
    handleRoleMenuScroll,
    rolesRefetch,
    handleUpdate,
  };
}
