"use client";

import { useMemo, useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import {
  bulkUpdateAttendancePermissions,
  getAllVolunteers,
  getAttendancePermissionsList,
} from "@/features/opportunities/services/attendance";
import { getApiErrorMessages } from "@/lib/api/errors";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import { permissionPerson, type PermissionRow } from "./attendancePermissionTypes";

/**
 * BE-69 — «إذن تحضير»: who, besides the organizer, may take attendance.
 *
 * Grant and revoke are one endpoint with `is_allowed` flipped, so they share a
 * mutation. Two rules are worth keeping in sight:
 *
 *  - someone who already holds the permission is filtered **out** of the
 *    candidate list, because offering them again would look like a second grant
 *    and do nothing;
 *  - the two endpoints disagree on where the person sits in the row — one nests
 *    under `user`, the other is flat — so `person()` reads both shapes rather
 *    than either list rendering blanks.
 */
export function useAttendancePermissions({
  opportunityId,
  selectedLanguage,
  t,
}: {
  opportunityId?: string;
  selectedLanguage: string;
  t: (key: string) => string;
}) {
  const [picking, setPicking] = useState(false);
  const [search, setSearch] = useState("");
  const debouncedSearch = useDebouncedValue(search);
  const [selected, setSelected] = useState<number[]>([]);
  const [revoking, setRevoking] = useState<number | null>(null);

  const bulkUpdate = useMutation({
    mutationFn: bulkUpdateAttendancePermissions,
  });


  const {
    data: holdersData,
    isFetching: loadingHolders,
    isError: holdersFailed,
    error: holdersError,
    refetch: refetchHolders,
  } = useQuery({
    queryKey: ["attendance-permissions", opportunityId],
    queryFn: () =>
      getAttendancePermissionsList({
        opportunity_id: opportunityId as string,
        limit: 100,
      }),
    enabled: Boolean(opportunityId),
  });

  const holders: PermissionRow[] = useMemo(
    () => holdersData?.data ?? [],
    [holdersData?.data]
  );

  const {
    data: candidatesData,
    isFetching: loadingCandidates,
    isError: candidatesFailed,
    error: candidatesError,
    refetch: refetchCandidates,
  } = useQuery({
    queryKey: ["all-volunteers", "attendance-permission", opportunityId, debouncedSearch],
    queryFn: () =>
      getAllVolunteers({
        opportunity_id: opportunityId,
        search: debouncedSearch,
        limit: 50,
      }),
    enabled: picking && Boolean(opportunityId),
  });

  /** Both endpoint shapes, read by `permissionPerson`. */
  const person = permissionPerson;

  const holderIds = useMemo(
    () => new Set(holders.map((row) => permissionPerson(row).id)),
    [holders]
  );

  const candidates: PermissionRow[] = useMemo(
    // Someone who already holds it is not a candidate — offering them again
    // would look like a second grant and do nothing.
    () =>
      (candidatesData?.data ?? []).filter(
        (row: PermissionRow) => !holderIds.has(permissionPerson(row).id)
      ),
    [candidatesData?.data, holderIds]
  );

  const reportError = (error: unknown) => {
    const messages = getApiErrorMessages(error, selectedLanguage);
    if (messages.length > 0) {
      messages.forEach((message) => toast.error(message));
    } else {
      toast.error(t("COMMON.UPDATE_FAILED"));
    }
  };

  const grant = async () => {
    if (!opportunityId || selected.length === 0) return;
    try {
      await bulkUpdate.mutateAsync({
        opportunity_id: opportunityId,
        user_ids: selected,
        is_allowed: true,
      });
      toast.success(t("COMMON.UPDATE_SUCCESS"));
      setSelected([]);
      setSearch("");
      setPicking(false);
      await refetchHolders();
    } catch (error) {
      reportError(error);
    }
  };

  const revoke = async (userId: number) => {
    if (!opportunityId) return;
    try {
      setRevoking(userId);
      await bulkUpdate.mutateAsync({
        opportunity_id: opportunityId,
        user_ids: [userId],
        is_allowed: false,
      });
      toast.success(t("COMMON.UPDATE_SUCCESS"));
      await refetchHolders();
    } catch (error) {
      reportError(error);
    } finally {
      setRevoking(null);
    }
  };

  return {
    picking,
    setPicking,
    search,
    setSearch,
    selected,
    setSelected,
    revoking,
    holders,
    candidates,
    loadingHolders,
    loadingCandidates,
    /** A failed read is not «no holders» / «no volunteers» (p.37). */
    holdersError: holdersFailed && holders.length === 0 ? holdersError : null,
    candidatesError: candidatesFailed ? candidatesError : null,
    retryHolders: () => void refetchHolders(),
    retryCandidates: () => void refetchCandidates(),
    isGranting: bulkUpdate.isPending,
    person,
    grant,
    revoke,
  };
}
