"use client";

import { useCallback, useEffect, useState } from "react";
import { BrandParticipantPaymentPanel } from "@/components/dashboard/BrandParticipantPaymentPanel";
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>
  );
}

function paymentStatusHint(participant: CampaignParticipant): string | null {
  if (participant.status !== "active") {
    return "Payment is only available for active creators.";
  }
  if (participant.payment_confirmed) {
    return "Payment successful";
  }
  if (participant.payment_method_authorized) {
    return "Payment method saved";
  }
  return "Authorize payment method";
}

export function BrandCampaignPaymentsTab({
  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 payments.");
    } finally {
      setIsLoading(false);
    }
  }, [campaignId]);

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

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

  if (isLoading) return <ListSkeleton />;

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

  if (participants.length === 0) {
    return (
      <EmptyState
        title="No payments yet"
        description="Payment authorization appears after creators join this campaign."
      />
    );
  }

  return (
    <div className="space-y-6">
      <p className="text-[0.8125rem] text-ink-60">
        Authorize a payment method for each creator. Once authorized, the card is charged
        automatically after required deliverables are verified.
      </p>
      {participants.map((participant) => {
        const displayName =
          participant.creator.display_name?.trim() || participant.creator.username;
        const hint = paymentStatusHint(participant);
        const isActive = participant.status === "active";

        return (
          <section
            key={participant.id}
            id={`payments-participant-${participant.id}`}
            className="space-y-3"
            aria-labelledby={`payments-heading-${participant.id}`}
          >
            <div className="flex flex-wrap items-center gap-2">
              <h3
                id={`payments-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>
              {hint ? (
                <span className="text-[0.75rem] text-ink-40">{hint}</span>
              ) : null}
            </div>
            {isActive ? (
              <BrandParticipantPaymentPanel
                campaignId={campaignId}
                participantId={participant.id}
                creatorName={displayName}
                participantActive
                paymentConfirmed={participant.payment_confirmed === true}
                paymentMethodAuthorized={participant.payment_method_authorized === true}
              />
            ) : (
              <p className="rounded-pv border border-line bg-surface px-3 py-3 text-[0.8125rem] text-ink-60">
                This creator was removed. Payment authorization is unavailable.
              </p>
            )}
          </section>
        );
      })}
    </div>
  );
}
