'use client';

import { InlineNotice } from '@/ui/InlineNotice';
import { ProgressLine } from '@/ui/ProgressLine';
import type { Result } from '@/lib/contracts/Result';
import type { SponsorshipRequestsViewData } from '@/lib/view-data/SponsorshipRequestsViewData';
import { SponsorshipRequestsTemplate } from '@/templates/SponsorshipRequestsTemplate';
import { Box } from '@/ui/Box';
import { useRouter } from 'next/navigation';
import { useState } from 'react';

interface SponsorshipRequestsClientProps {
  viewData: SponsorshipRequestsViewData;
  onAccept: (requestId: string) => Promise<Result<void, string>>;
  onReject: (requestId: string, reason?: string) => Promise<Result<void, string>>;
}

export function SponsorshipRequestsClient({ viewData, onAccept, onReject }: SponsorshipRequestsClientProps) {
  const router = useRouter();
  const [isProcessing, setIsProcessing] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handleAccept = async (requestId: string) => {
    setIsProcessing(requestId);
    setError(null);
    const result = await onAccept(requestId);
    if (result.isErr()) {
      setError(result.getError());
      setIsProcessing(null);
    } else {
      router.refresh();
      setIsProcessing(null);
    }
  };

  const handleReject = async (requestId: string, reason?: string) => {
    setIsProcessing(requestId);
    setError(null);
    const result = await onReject(requestId, reason);
    if (result.isErr()) {
      setError(result.getError());
      setIsProcessing(null);
    } else {
      router.refresh();
      setIsProcessing(null);
    }
  };

  return (
    <>
      <ProgressLine isLoading={!!isProcessing} />
      {error && (
        <Box position="fixed" top={4} right={4} zIndex={50} maxWidth="md">
          <InlineNotice
            variant="error"
            title="Action Failed"
            message={error}
          />
        </Box>
      )}
      <SponsorshipRequestsTemplate
        viewData={viewData}
        onAccept={handleAccept}
        onReject={handleReject}
        processingId={isProcessing}
      />
    </>
  );
}
