import { Button } from '@/components/ui/button';
import { useCurrency } from '@/hooks/use-currency';
import { useApiSWR } from '@/hooks/useSWR';
import { handleApiError } from '@/lib/error-handler';
import { request } from '@/lib/fetcher';
import { TOrder } from '@/types/market.types';
import { XIcon } from '@phosphor-icons/react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

/**
 * The user's resting orders for a market, with cancel. Revalidates on the
 * `refreshKey` bump the parent raises when the book changes.
 */
export default function OpenOrders({
  slug,
  refreshKey,
}: {
  slug: string;
  refreshKey: number;
}) {
  const { t } = useTranslation();
  const { format } = useCurrency();
  const [cancelling, setCancelling] = useState<number | null>(null);

  const { data, mutate } = useApiSWR<{ data: TOrder[] }>(
    `/user/markets/${slug}/orders?_k=${refreshKey}`,
  );

  const resting = (data?.data ?? []).filter(
    (o) => o.status === 'open' || o.status === 'partial',
  );

  const cancel = async (id: number) => {
    setCancelling(id);
    try {
      await request.delete(`/api/user/markets/${slug}/orders/${id}`);
      toast.success(t('Order cancelled.'));
      mutate();
    } catch (e) {
      handleApiError(e);
    } finally {
      setCancelling(null);
    }
  };

  if (resting.length === 0) {
    return (
      <p className="py-4 text-center text-xs text-black/40 dark:text-white/40">
        {t('No open orders.')}
      </p>
    );
  }

  return (
    <ul className="divide-y divide-black/5 dark:divide-white/10">
      {resting.map((o) => {
        const remaining =
          (Number(o.original_qty) || 0) - (Number(o.filled_qty) || 0);
        return (
          <li key={o.id} className="flex items-center gap-3 py-2.5 text-sm">
            <span
              className={`text-xs font-semibold uppercase ${o.side === 'buy' ? 'text-pm-yes' : 'text-pm-no'}`}
            >
              {o.side}
            </span>
            <div className="min-w-0 flex-1">
              <p className="truncate font-medium">
                {o.outcome?.title ?? t('Outcome')}
              </p>
              <p className="text-xs text-black/40 dark:text-white/40">
                {o.limit_price != null
                  ? format(Number(o.limit_price))
                  : t('Market')}
                {o.original_qty != null &&
                  ` · ${remaining.toLocaleString(undefined, { maximumFractionDigits: 2 })} ${t('left')}`}
                {o.status === 'partial' && ` · ${t('partial')}`}
              </p>
            </div>
            <Button
              variant="ghost"
              size="icon"
              className="size-8 shrink-0"
              loading={cancelling === o.id}
              onClick={() => cancel(o.id)}
              title={t('Cancel')}
            >
              <XIcon weight="bold" className="size-4" />
            </Button>
          </li>
        );
      })}
    </ul>
  );
}
