"use client";

import { useCallback, useEffect, useState } from "react";
import { Spinner } from "@nextui-org/react";

import Button from "@/components/common/button";
import { useClientPortalAuth } from "@/components/pages/client/participant-list/common/client-portal-auth-context";
import ParticipantList from "@/components/pages/client/participant-list/participants/participant-list";
import {
  getParticipantsForPortal,
  getResearchersForPortal,
} from "@/services/client/participant-list/portal-actions";
import {
  FieldConfig,
  Participant,
  ProjectOverview,
} from "@/types/participant-list/provisional-types";

type ParticipantPageData = {
  participants: Participant[];
  project: ProjectOverview;
  visibility: FieldConfig[];
  researchers: string[];
};

export default function ParticipantListPage() {
  const { auth, handlePortalStatus } = useClientPortalAuth();
  const [data, setData] = useState<ParticipantPageData | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const load = useCallback(async () => {
    if (!auth) return;
    setIsLoading(true);
    setError(null);
    try {
      const [participants, researchers] = await Promise.all([
        getParticipantsForPortal(auth),
        getResearchersForPortal(auth),
      ]);
      const failed = !participants.ok
        ? participants
        : !researchers.ok
          ? researchers
          : null;
      if (failed) {
        if (!handlePortalStatus(failed.status)) {
          setError("We couldn't load the participant list. Please try again.");
        }
      } else if (participants.ok && researchers.ok) {
        setData({ ...participants.data, researchers: researchers.data });
      }
    } catch {
      setError("We couldn't load the participant list. Please try again.");
    } finally {
      setIsLoading(false);
    }
  }, [auth, handlePortalStatus]);

  useEffect(() => {
    void load();
  }, [load]);

  if (isLoading) {
    return (
      <div className="flex min-h-[50vh] items-center justify-center">
        <Spinner label="Loading participants…" />
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="mx-auto max-w-md px-4 py-16 text-center">
        <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
        <Button
          btnLabel="Try again"
          className="mt-4"
          customVariant="client"
          onClick={() => void load()}
        />
      </div>
    );
  }

  return (
    <ParticipantList
      participants={data.participants}
      project={data.project}
      researchers={data.researchers}
      visibilityControls={data.visibility}
    />
  );
}
