"use client";

import { useCallback, useEffect, useState } from "react";
import { BrandParticipantDeliverablesPanel } from "@/components/dashboard/BrandParticipantDeliverablesPanel";
import { EmptyState } from "@/components/ui/EmptyState";
import { ErrorState } from "@/components/ui/ErrorState";
import { Skeleton } from "@/components/ui/Skeleton";
import { StatusBadge } from "@/components/ui/StatusBadge";
import { ApiError } from "@/lib/api";
import { participantApi } from "@/lib/api/campaign-participation";
import {
  participantStatusBadgeVariant,
  participantStatusLabel,
} from "@/lib/campaign-participation";
import type { CampaignParticipant } from "@/types/campaign-participation";

function ListSkeleton() {
  return (
    <div className="space-y-3">
      <Skeleton className="h-28 w-full" />
      <Skeleton className="h-28 w-full" />
    </div>
  );
}

export function BrandCampaignDeliverablesTab({
  campaignId,
  focusParticipantId = null,
}: {
  campaignId: number;
  focusParticipantId?: number | null;
}) {
  const [participants, setParticipants] = useState<CampaignParticipant[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const result = await participantApi.listForCampaign(campaignId, { per_page: 50 });
      setParticipants(result.participants);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Unable to load deliverables.");
    } finally {
      setIsLoading(false);
    }
  }, [campaignId]);

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

  useEffect(() => {
    if (focusParticipantId == null || isLoading) return;
    const node = document.getElementById(`deliverables-participant-${focusParticipantId}`);
    node?.scrollIntoView({ behavior: "smooth", block: "start" });
  }, [focusParticipantId, isLoading, participants]);

  if (isLoading) return <ListSkeleton />;

  if (error) {
    return (
      <ErrorState
        title="Couldn’t load deliverables"
        message={error}
        retryLabel="Retry"
        onRetry={() => void load()}
      />
    );
  }

  if (participants.length === 0) {
    return (
      <EmptyState
        title="No deliverables assigned yet"
        description="Deliverables appear after creators join this campaign."
      />
    );
  }

  return (
    <div className="space-y-6">
      {participants.map((participant) => {
        const displayName =
          participant.creator.display_name?.trim() || participant.creator.username;
        return (
          <section
            key={participant.id}
            id={`deliverables-participant-${participant.id}`}
            className="space-y-3"
            aria-labelledby={`deliverables-heading-${participant.id}`}
          >
            <div className="flex flex-wrap items-center gap-2">
              <h3
                id={`deliverables-heading-${participant.id}`}
                className="text-[0.9375rem] font-semibold text-primary"
              >
                {displayName}
              </h3>
              <span className="text-[0.75rem] text-ink-40">@{participant.creator.username}</span>
              <StatusBadge variant={participantStatusBadgeVariant(participant.status)}>
                {participantStatusLabel(participant.status)}
              </StatusBadge>
            </div>
            <BrandParticipantDeliverablesPanel
              campaignId={campaignId}
              participantId={participant.id}
              creatorLabel={displayName}
            />
          </section>
        );
      })}
    </div>
  );
}
