'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 fetchHistoryDeals(): Promise<ApiDeal[]> {
  const res = await fetchWithRefresh('/api/vendor/deals/list?tab=history');
  if (!res.ok) throw new Error('fetch-failed');
  const json = (await res.json()) as { ok: boolean; deals: ApiDeal[] };
  return json.deals;
}

function HistoryListSkeleton() {
  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 VendorDealsHistoryInner() {
  const t = useT('vendor_deals_history');
  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', 'history'],
    queryFn: fetchHistoryDeals,
  });

  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' });
    },
  });

  const header = (
    <header>
      <h1 className="text-text-primary text-2xl font-bold">{t('page_heading')}</h1>
      <p className="text-text-secondary mt-1 text-sm">{t('page_subtitle')}</p>
    </header>
  );

  if (status === 'pending') {
    return (
      <div className="flex flex-col gap-4">
        {header}
        <HistoryListSkeleton />
      </div>
    );
  }
  if (isError) {
    return (
      <div className="flex flex-col gap-4">
        {header}
        <ErrorState
          title={tCommon('error_loading')}
          action={
            <Button variant="secondary" size="sm" onClick={() => refetch()}>
              {tCommon('retry')}
            </Button>
          }
        />
      </div>
    );
  }

  if (data.length === 0) {
    return (
      <div className="flex flex-col gap-4">
        {header}
        <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>
          }
        />
      </div>
    );
  }

  return (
    <ErrorBoundary>
      <div className="flex flex-col gap-4">
        {header}
        <ul className={cn('flex flex-col gap-3')}>
          {data.map((deal) => (
            <li key={deal.id} className="relative">
              <a
                href={`/vendor/deals/${deal.id}`}
                className="absolute inset-0 z-0 rounded-2xl focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-brand-primary-600)]"
                aria-label={deal.title}
              />
              <div className="pointer-events-none relative z-10 [&_button]:pointer-events-auto">
                <VendorDealCard
                  variant="history"
                  title={deal.title}
                  dealStateLabel={
                    deal.dealState === 'EXPIRED' ? t('state_expired') : t('state_paused')
                  }
                  dealStateLabelTooltip={
                    deal.dealState === 'EXPIRED'
                      ? t('state_expired_tooltip')
                      : t('state_paused_tooltip')
                  }
                  participants={deal.quantitySold}
                  targetParticipants={deal.quantityTotal}
                  dealDate={deal.createdAt ? formatDateLocale(deal.createdAt, locale) : undefined}
                  onDuplicate={() =>
                    duplicateMutation.mutate({
                      dealId: deal.id,
                      idempotencyKey: getDuplicateIdempotencyKey(duplicateKeys.current, deal.id),
                    })
                  }
                  duplicateLoading={
                    duplicateMutation.isPending && duplicateMutation.variables?.dealId === deal.id
                  }
                />
              </div>
            </li>
          ))}
        </ul>
      </div>
    </ErrorBoundary>
  );
}

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