import React, { useState, useEffect } from 'react';
import { JackpotCard } from './JackpotCard';
import { JackpotSheet } from './JackpotSheet';
import { useJackpot } from '../../hooks/useJackpot';
import { useDubs } from '../../provider';
import type { EnterJackpotMutationResult } from '../../hooks/useEnterJackpot';
import type { JackpotEntry } from '../../types';
import type { ViewStyle } from 'react-native';

export interface JackpotWidgetProps {
  /** Style applied to the card */
  style?: ViewStyle;
  /** Minimum entry in SOL (default: 0.01) */
  minEntry?: number;
  /** Maximum entry in SOL (default: 10) */
  maxEntry?: number;
  /** Callback when a jackpot entry succeeds */
  onEntry?: (result: EnterJackpotMutationResult) => void;
  /** Callback on entry error */
  onError?: (error: Error) => void;
}

/**
 * Self-contained Jackpot widget — the first "crypto ad".
 *
 * Drop `<JackpotWidget />` anywhere in your app. Shows a live jackpot card
 * matching the web lobby design with pot amount, player carousel, and
 * Place Bet button. Tapping opens a scrollable sheet with full entry flow.
 */
export function JackpotWidget({
  style,
  minEntry,
  maxEntry,
  onEntry,
  onError,
}: JackpotWidgetProps) {
  const [sheetVisible, setSheetVisible] = useState(false);
  const { round, lastWinner } = useJackpot();
  const { client } = useDubs();
  const [entries, setEntries] = useState<JackpotEntry[]>([]);

  // Fetch entries for the card carousel
  useEffect(() => {
    client.getJackpotEntries()
      .then(res => setEntries(res.entries))
      .catch(() => {});
  }, [client, round?.entryCount]);

  return (
    <>
      <JackpotCard
        round={round}
        lastWinner={lastWinner}
        entries={entries}
        onPress={() => setSheetVisible(true)}
        style={style}
      />
      <JackpotSheet
        visible={sheetVisible}
        onDismiss={() => setSheetVisible(false)}
        onSuccess={(result) => {
          onEntry?.(result);
          // Refresh entries after entry
          client.getJackpotEntries()
            .then(res => setEntries(res.entries))
            .catch(() => {});
        }}
        onError={onError}
        minEntry={minEntry}
        maxEntry={maxEntry}
      />
    </>
  );
}
