"use client";

import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import {
  BanknotesIcon,
  EyeIcon,
  MagnifyingGlassIcon,
  PhotoIcon,
  UserMinusIcon,
} from "@heroicons/react/24/outline";
import { Button } from "@/components/Button";
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, publicProfilePath } from "@/lib/api";
import { participantApi } from "@/lib/api/campaign-participation";
import { participantSourceLabel } from "@/lib/campaign-management";
import {
  participantStatusBadgeVariant,
  participantStatusLabel,
} from "@/lib/campaign-participation";
import { formatDateShort, formatFollowerCount, formatRelativeTime } from "@/lib/format";
import { socialProviderLabel } from "@/lib/social-providers";
import type { CampaignParticipant } from "@/types/campaign-participation";

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

function CreatorAvatar({
  name,
  imageUrl,
}: {
  name: string;
  imageUrl: string | null;
}) {
  const initial = name.trim().charAt(0).toUpperCase() || "?";
  if (imageUrl) {
    return (
      // eslint-disable-next-line @next/next/no-img-element -- remote API profile URLs
      <img
        src={imageUrl}
        alt=""
        className="h-10 w-10 shrink-0 rounded-full object-cover"
      />
    );
  }
  return (
    <span
      aria-hidden
      className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-line text-[0.8125rem] font-semibold text-primary"
    >
      {initial}
    </span>
  );
}

function paymentActionLabel(participant: CampaignParticipant): string {
  if (participant.payment_confirmed) return "View payment";
  if (participant.payment_method_authorized) return "View payment";
  return "Authorize payment";
}

export function BrandCampaignParticipantsTab({
  campaignId,
  onViewDeliverables,
  onViewPayment,
  onGoToApplications,
  discoverHref,
}: {
  campaignId: number;
  onViewDeliverables: (participantId: number) => void;
  onViewPayment: (participantId: number) => void;
  onGoToApplications?: () => void;
  discoverHref?: string;
}) {
  const [participants, setParticipants] = useState<CampaignParticipant[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [busyKey, setBusyKey] = 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 participants.");
    } finally {
      setIsLoading(false);
    }
  }, [campaignId]);

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

  async function handleRemove(participantId: number) {
    const confirmed = window.confirm("Remove this participant from the campaign?");
    if (!confirmed) return;

    setBusyKey(`remove-${participantId}`);
    try {
      await participantApi.remove(participantId);
      toast.success("Participant removed.");
      await load();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "Unable to remove participant.");
    } finally {
      setBusyKey(null);
    }
  }

  if (isLoading) return <ListSkeleton />;

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

  if (participants.length === 0) {
    return (
      <EmptyState
        title="No creators yet"
        description="Creators appear here after they accept an invite or you accept their application."
        action={
          <div className="flex flex-wrap justify-center gap-2">
            {discoverHref ? (
              <Button size="sm" href={discoverHref}>
                <MagnifyingGlassIcon className="size-4" aria-hidden="true" />
                <span>Discover creators</span>
              </Button>
            ) : null}
            {onGoToApplications ? (
              <Button size="sm" variant="secondary" onClick={onGoToApplications}>
                Applications
              </Button>
            ) : null}
          </div>
        }
      />
    );
  }

  return (
    <ul className="divide-y divide-line rounded-pv border border-line bg-surface">
      {participants.map((participant) => {
        const displayName =
          participant.creator.display_name?.trim() || participant.creator.username;
        const hasSocial =
          participant.creator.platforms.length > 0 || participant.creator.followers != null;
        const isRemoved = participant.status === "removed";

        return (
          <li
            key={participant.id}
            className={`flex flex-col gap-3 px-3 py-3 sm:flex-row sm:items-start sm:justify-between ${
              isRemoved ? "opacity-70" : ""
            }`}
          >
            <div className="flex min-w-0 gap-3">
              <CreatorAvatar name={displayName} imageUrl={participant.creator.profile_image} />
              <div className="min-w-0 space-y-1">
                <p className="truncate text-[0.875rem] font-medium text-primary">{displayName}</p>
                <p className="text-[0.75rem] text-ink-40">@{participant.creator.username}</p>
                <p className="text-[0.75rem] text-ink-60">
                  Via {participantSourceLabel(participant.source)}
                  {" · Joined "}
                  {formatDateShort(participant.joined_at.slice(0, 10))}
                  {participant.left_at
                    ? ` · Left ${formatRelativeTime(participant.left_at)}`
                    : null}
                </p>
                {hasSocial ? (
                  <p className="text-[0.75rem] text-ink-40">
                    {participant.creator.platforms.length > 0
                      ? participant.creator.platforms.map((p) => socialProviderLabel(p)).join(", ")
                      : null}
                    {participant.creator.followers != null
                      ? `${participant.creator.platforms.length > 0 ? " · " : ""}${formatFollowerCount(participant.creator.followers)} followers`
                      : null}
                  </p>
                ) : null}
              </div>
            </div>

            <div className="flex flex-wrap items-center gap-2 sm:justify-end">
              <StatusBadge variant={participantStatusBadgeVariant(participant.status)}>
                {participantStatusLabel(participant.status)}
              </StatusBadge>
              <Button
                size="sm"
                variant="secondary"
                href={publicProfilePath(participant.creator.username)}
              >
                <EyeIcon className="size-4" aria-hidden="true" />
                <span>View creator</span>
              </Button>
              <Button
                size="sm"
                variant="secondary"
                onClick={() => onViewDeliverables(participant.id)}
              >
                <PhotoIcon className="size-4" aria-hidden="true" />
                <span>View deliverables</span>
              </Button>
              {!isRemoved ? (
                <Button
                  size="sm"
                  variant="secondary"
                  onClick={() => onViewPayment(participant.id)}
                >
                  <BanknotesIcon className="size-4" aria-hidden="true" />
                  <span>{paymentActionLabel(participant)}</span>
                </Button>
              ) : null}
              {participant.status === "active" ? (
                <Button
                  size="sm"
                  variant="secondary"
                  disabled={busyKey === `remove-${participant.id}`}
                  onClick={() => void handleRemove(participant.id)}
                >
                  <UserMinusIcon className="size-4" aria-hidden="true" />
                  <span>
                    {busyKey === `remove-${participant.id}` ? "Removing…" : "Remove"}
                  </span>
                </Button>
              ) : null}
            </div>
          </li>
        );
      })}
    </ul>
  );
}
