import { Button } from '@/components/ui/button';
import { handleApiError } from '@/lib/error-handler';
import { request } from '@/lib/fetcher';
import { DownloadSimpleIcon } from '@phosphor-icons/react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

export type UmaLookup = {
  market_id: string;
  question: string | null;
  outcomes: string[];
  closes_at: string | null;
  resolved: boolean;
};

/**
 * Pulls a Polymarket/UMA market's question, outcomes and close date via the
 * Gamma lookup endpoint and hands them to the parent form to auto-populate a
 * mirror market. Uses the market id already entered in the oracle config.
 */
export default function UmaImport({
  form,
  onImported,
}: {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  form: any;
  onImported: (data: UmaLookup) => void;
}) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);

  const marketId: string | undefined = form.watch('oracle_config.market_id');

  const handleImport = async () => {
    if (!marketId) {
      toast.error(t('Enter a Polymarket market id first.'));
      return;
    }
    setLoading(true);
    try {
      const { data } = await request.get('/api/admin/markets/uma-lookup', {
        params: { market_id: marketId },
      });
      onImported(data as UmaLookup);
      toast.success(t('Imported details from Polymarket.'));
    } catch (error) {
      handleApiError(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex items-center justify-between rounded-xl border border-dashed border-black/10 p-4 dark:border-white/15">
      <div>
        <p className="text-sm font-medium">{t('Import from Polymarket')}</p>
        <p className="text-xs text-black/50 dark:text-white/50">
          {t(
            'Fill the title, outcomes and close date from the Polymarket market above.',
          )}
        </p>
      </div>
      <Button
        type="button"
        variant="outline"
        loading={loading}
        disabled={loading || !marketId}
        onClick={handleImport}
      >
        <DownloadSimpleIcon weight="bold" className="mr-1.5 size-4" />
        {t('Import')}
      </Button>
    </div>
  );
}
