'use client';

import { useRef } from 'react';
import { getDuplicateIdempotencyKey } from './duplicate-idempotency';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { HydratedIsland } from '@/components/HydratedIsland';
import { VendorShell } from '@/components/ui/layout/VendorShell';
import { VendorDealCard } from '@/components/ui/domain/vendor/VendorDealCard';
import { Skeleton } from '@/components/ui/feedback/Skeleton';
import { EmptyState } from '@/components/ui/feedback/EmptyState';
import { ErrorState } from '@/components/ui/feedback/ErrorState';
import { Button } from '@/components/ui/primitives/Button';
import { useLocale, useT } from '@/lib/i18n/react';
import { fetchWithRefresh } from '@/lib/api/refresh-on-401';
import { ErrorBoundary } from '@/components/ui/feedback/ErrorBoundary';
import { cn } from '@/lib/cn';
import { formatDateLocale } from '@/lib/datetime';
import { getCsrfToken } from '@/lib/csrf';
import { useToast } from '@/components/ui/overlays/Toast/useToast';

interface ApiDeal {
  id: string;
  title: string;
  dealState: string;
  quantityTotal: number;
  quantitySold: number;
  createdAt?: string | null;
}

async function fetchSoldDeals(): Promise<ApiDeal[]> {
  const res = await fetchWithRefresh('/api/vendor/deals/list?tab=sold');
  if (!res.ok) throw new Error('fetch-failed');
  const json = (await res.json()) as { ok: boolean; deals: ApiDeal[] };
  return json.deals;
}

function SoldListSkeleton() {
  return (
    <ul aria-busy="true" className="flex flex-col gap-3">
      {(['skeleton-1', 'skeleton-2', 'skeleton-3'] as const).map((skeletonKey) => (
        <li key={skeletonKey}>
          <Skeleton className="h-28 w-full rounded-2xl" />
        </li>
      ))}
    </ul>
  );
}

function VendorDealsSoldInner() {
  const t = useT('vendor_deals_sold');
  const tDeals = useT('vendor_deals');
  const tCommon = useT('common');
  const { locale } = useLocale();
  const qc = useQueryClient();
  const { toast } = useToast();
  const duplicateKeys = useRef(new Map<string, string>());

  const { data, status, refetch, isError } = useQuery({
    queryKey: ['vendor-deals', 'sold'],
    queryFn: fetchSoldDeals,
  });

  const duplicateMutation = useMutation({
    mutationFn: async ({ dealId, idempotencyKey }: { dealId: string; idempotencyKey: string }) => {
      const csrf = getCsrfToken();
      const res = await fetch(`/api/vendor/deals/${dealId}/duplicate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-csrf-token': csrf,
          'idempotency-key': idempotencyKey,
        },
        body: '{}',
      });
      const json = (await res.json()) as { ok: boolean; deal?: { id: string } };
      if (!json.ok) throw new Error(tDeals('duplicate_error'));
      return json.deal!;
    },
    onSuccess: (newDeal) => {
      void qc.invalidateQueries({ queryKey: ['vendor-deals', 'drafts'] });
      window.location.href = `/vendor/deals/${newDeal.id}`;
    },
    onError: () => {
      toast({ title: tDeals('duplicate_error'), tone: 'danger' });
    },
  });

  if (status === 'pending') {
    return <SoldListSkeleton />;
  }
  if (isError) {
    return (
      <ErrorState
        title={t('error_loading')}
        action={
          <Button variant="secondary" size="sm" onClick={() => refetch()}>
            {tCommon('retry')}
          </Button>
        }
      />
    );
  }

  if (data.length === 0) {
    return (
      <EmptyState
        title={t('empty_title')}
        description={t('empty_desc')}
        action={
          <Button
            variant="primary"
            size="sm"
            onClick={() => (window.location.href = '/vendor/deals/new')}
          >
            {t('empty_cta')}
          </Button>
        }
      />
    );
  }

  return (
    <ErrorBoundary>
      <ul className={cn('flex flex-col gap-3')}>
        {data.map((deal) => (
          <li key={deal.id}>
            <VendorDealCard
              variant="history"
              title={deal.title}
              outcome="sold_out"
              participants={deal.quantitySold}
              targetParticipants={deal.quantityTotal}
              dealDate={deal.createdAt ? formatDateLocale(deal.createdAt, locale) : undefined}
              dealDateLabel={t('published_at_label')}
              onDuplicate={() =>
                duplicateMutation.mutate({
                  dealId: deal.id,
                  idempotencyKey: getDuplicateIdempotencyKey(duplicateKeys.current, deal.id),
                })
              }
              duplicateLoading={
                duplicateMutation.isPending && duplicateMutation.variables?.dealId === deal.id
              }
            />
          </li>
        ))}
      </ul>
    </ErrorBoundary>
  );
}

export function VendorDealsSold() {
  return (
    <VendorShell variant="dashboard" currentPath="/vendor/deals/sold">
      <div className="flex flex-col gap-6 p-4 lg:p-6">
        <HydratedIsland>
          <VendorDealsSoldInner />
        </HydratedIsland>
      </div>
    </VendorShell>
  );
}
