'use client';

import { useMemo, useRef, useState } 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 { FilterChip } from '@/components/ui/primitives/FilterChip';
import { useLocale, useT } from '@/lib/i18n/react';
import { formatDateLocale } from '@/lib/datetime';
import { fetchWithRefresh } from '@/lib/api/refresh-on-401';
import { ErrorBoundary } from '@/components/ui/feedback/ErrorBoundary';
import { cn } from '@/lib/cn';
import { getCsrfToken } from '@/lib/csrf';
import { useToast } from '@/components/ui/overlays/Toast/useToast';

type ClosedDealState = 'EXPIRED' | 'PAUSED' | 'SOLD_OUT';
type StateFilter = 'all' | ClosedDealState;

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

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

async function fetchClosedDeals(): Promise<ApiDeal[]> {
  const [closed, history, sold] = await Promise.all([
    fetchTabDeals('closed'),
    fetchTabDeals('history'),
    fetchTabDeals('sold'),
  ]);

  const byId = new Map<string, ApiDeal>();
  for (const deal of [...closed, ...history, ...sold]) {
    if (['EXPIRED', 'PAUSED', 'SOLD_OUT'].includes(deal.dealState)) {
      byId.set(deal.id, deal);
    }
  }

  return [...byId.values()].sort((a, b) => {
    const aTime = a.createdAt ? Date.parse(a.createdAt) : 0;
    const bTime = b.createdAt ? Date.parse(b.createdAt) : 0;
    return bTime - aTime;
  });
}

const STATE_FILTERS: StateFilter[] = ['all', 'EXPIRED', 'PAUSED', 'SOLD_OUT'];

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

function VendorDealsClosedInner() {
  const t = useT('vendor_deals_closed');
  const tDeals = useT('vendor_deals');
  const tCommon = useT('common');
  const { locale } = useLocale();
  const qc = useQueryClient();
  const { toast } = useToast();
  const [stateFilter, setStateFilter] = useState<StateFilter>('all');
  const duplicateKeys = useRef(new Map<string, string>());

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

  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 filteredDeals = useMemo(() => {
    if (!data) return [];
    if (stateFilter === 'all') return data;
    return data.filter((deal) => deal.dealState === stateFilter);
  }, [data, stateFilter]);

  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>
  );

  const filterPills = (
    <div className="flex flex-wrap gap-2" role="group" aria-label={t('filter_label')}>
      {STATE_FILTERS.map((filter) => (
        <FilterChip
          key={filter}
          pressed={stateFilter === filter}
          onClick={() => setStateFilter(filter)}
        >
          {filter === 'all'
            ? t('filter_all')
            : filter === 'EXPIRED'
              ? t('filter_expired')
              : filter === 'PAUSED'
                ? t('filter_paused')
                : t('filter_sold_out')}
        </FilterChip>
      ))}
    </div>
  );

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

  if (filteredDeals.length === 0) {
    return (
      <div className="flex flex-col gap-4">
        {header}
        {filterPills}
        <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}
        {filterPills}
        <ul className={cn('flex flex-col gap-3')}>
          {filteredDeals.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')
                      : deal.dealState === 'PAUSED'
                        ? t('state_paused')
                        : t('state_sold_out')
                  }
                  dealStateLabelTooltip={
                    deal.dealState === 'EXPIRED'
                      ? t('state_expired_tooltip')
                      : deal.dealState === 'PAUSED'
                        ? t('state_paused_tooltip')
                        : t('state_sold_out_tooltip')
                  }
                  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
                  }
                />
              </div>
            </li>
          ))}
        </ul>
      </div>
    </ErrorBoundary>
  );
}

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