import React, { useEffect, useMemo, useState } from 'react';
import { Text, View } from 'react-native';
import { CreditCard } from 'lucide-react-native';

import { conversationStyles } from '../../features/conversation/conversationStyles';
import type { SuperagentToolRendererProps } from '../../types';
import {
  formatMethods,
  normalizeProviders,
  parsePspToolErrorMessage,
  selectPaymentProviderTitle,
  showsPspForm,
} from '../interactiveWidgetUtils';
import { ApprovalCard } from '../primitives/ApprovalCard';
import { toolWidgetStyles } from '../primitives/toolWidgetStyles';
import { getWidgetStatus, parseToolArgs } from '../toolWidgetUtils';
import { useApprovalSubmit } from '../useApprovalSubmit';
import { FallbackActionCard, SelectableOptionRow, StatusRowWithError } from './interactiveWidgetParts';

/**
 * select_payment_provider — native port of the web SelectPaymentProvider
 * radio picker. Both actions resolve the call as approved: Continue submits
 * {processor_type}, Skip submits {skipped: true} (the backend treats skip as
 * a successful resolution, not a rejection). The form renders for waiting AND
 * error (the backend keeps this tool submittable on error for in-place retry
 * — web showForm parity, with the failure reason shown above the picker),
 * gated on isLastAssistantMessage so a stale card can't resume an old turn
 * out of order.
 */
export function SelectPaymentProviderWidget({ isLastAssistantMessage, submitToolCallInput, toolCall }: SuperagentToolRendererProps) {
  const args = useMemo(() => parseToolArgs(toolCall), [toolCall]);
  const providers = useMemo(() => normalizeProviders(args), [args]);
  const status = getWidgetStatus(toolCall.status);
  const { canAct, error, isSubmitting, submit } = useApprovalSubmit(toolCall, submitToolCallInput);
  const [selected, setSelected] = useState<string | null>(providers[0]?.key ?? null);

  // The card can mount before the prepare hook's trusted provider list arrives
  // (streaming) — re-seed the selection whenever the list changes and the
  // current pick is no longer in it (web useSelectPaymentProvider parity).
  const providerKeys = providers.map((provider) => provider.key).join(' ');
  useEffect(() => {
    setSelected((current) => (providers.some((provider) => provider.key === current)
      ? current
      : (providers[0]?.key ?? null)));
    // providers is recomputed per render; key off the stable joined-keys string.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [providerKeys]);

  const resultError = status === 'error' ? parsePspToolErrorMessage(toolCall.results) : null;

  if (showsPspForm(status, isLastAssistantMessage)) {
    if (providers.length === 0) {
      return (
        <FallbackActionCard
          buttonLabel="Continue without connecting"
          error={error}
          isSubmitting={isSubmitting}
          message={resultError ??
            ("We couldn't load the available payment providers for your region. You can " +
              "complete the connection from the Payments dashboard (the Payments button in " +
              "your app's dashboard) when you're ready.")}
          onPress={canAct ? () => submit(true, { skipped: true }) : undefined}
        />
      );
    }

    return (
      <ApprovalCard
        approveDisabled={!selected}
        approveLabel="Continue"
        error={error}
        isSubmitting={isSubmitting}
        onApprove={canAct ? () => { if (selected) void submit(true, { processor_type: selected }); } : undefined}
        onReject={canAct ? () => submit(true, { skipped: true }) : undefined}
        rejectLabel="Skip for now"
        title="Choose a payment provider"
      >
        <Text style={toolWidgetStyles.interactiveBodyText}>
          Choose a payment provider to activate payments.
        </Text>
        {resultError ? <Text style={conversationStyles.toolApprovalError}>{resultError}</Text> : null}
        <View style={toolWidgetStyles.optionList}>
          {providers.map((provider) => (
            <SelectableOptionRow
              disabled={isSubmitting}
              key={provider.key}
              label={provider.display_name}
              onPress={() => setSelected(provider.key)}
              selected={selected === provider.key}
              subtitle={provider.methods.length > 0 ? formatMethods(provider.methods) : null}
            />
          ))}
        </View>
      </ApprovalCard>
    );
  }

  return (
    <StatusRowWithError
      errorMessage={resultError}
      icon={CreditCard}
      status={status}
      title={selectPaymentProviderTitle(status, toolCall.results)}
    />
  );
}
