/**
 * Get full path quote (swap+bridge+swap) when VITE_BRIDGE_QUOTE_URL is set.
 * Calls POST /api/bridge/quote with sourceToken, destinationToken, sourceChainId, destinationChainId, amount.
 */

import { useState } from 'react';
import { BRIDGE_QUOTE_URL } from '../../config/bridge';
import { defaultFrontendChainId } from '../../config/networks';

interface QuoteResult {
  transferId?: string;
  minReceived?: string;
  sourceSwapQuote?: string;
  destinationSwapQuote?: string;
  totalFee?: string;
  estimatedTime?: number;
  routes?: unknown[];
}

export default function SwapBridgeSwapQuoteForm() {
  const [sourceToken, setSourceToken] = useState('');
  const [destinationToken, setDestinationToken] = useState('');
  const [sourceChainId, setSourceChainId] = useState(String(defaultFrontendChainId));
  const [destinationChainId, setDestinationChainId] = useState('137');
  const [amount, setAmount] = useState('');
  const [quote, setQuote] = useState<QuoteResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (!BRIDGE_QUOTE_URL) return null;

  const handleGetQuote = async () => {
    if (!amount) {
      setError('Enter amount');
      return;
    }
    setError(null);
    setQuote(null);
    setLoading(true);
    try {
      const url = `${BRIDGE_QUOTE_URL.replace(/\/$/, '')}/api/bridge/quote`;
      const res = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          sourceToken: sourceToken || undefined,
          destinationToken: destinationToken || undefined,
          sourceChainId: sourceChainId ? Number(sourceChainId) : undefined,
          destinationChainId: Number(destinationChainId),
          amount: amount,
          token: sourceToken || '0x0000000000000000000000000000000000000000',
          destinationAddress: '0x0000000000000000000000000000000000000000',
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || `Quote failed: ${res.status}`);
      }
      const data = await res.json();
      setQuote(data);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to get quote');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="mb-6 p-4 rounded-xl bg-[#1a1d24] border border-white/10">
      <h3 className="text-sm font-semibold text-[#A0A0A0] mb-3">Get full path quote (swap+bridge+swap)</h3>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
        <label htmlFor="quote-source-token" className="sr-only">Source token address</label>
        <input
          id="quote-source-token"
          name="sourceToken"
          type="text"
          placeholder="Source token address"
          value={sourceToken}
          onChange={(e) => setSourceToken(e.target.value)}
          className="px-3 py-2 rounded-lg bg-[#252830] text-white border border-white/20 focus:ring-2 focus:ring-teal-500/50 placeholder:text-[#A0A0A0]"
        />
        <label htmlFor="quote-destination-token" className="sr-only">Destination token address</label>
        <input
          id="quote-destination-token"
          name="destinationToken"
          type="text"
          placeholder="Destination token address"
          value={destinationToken}
          onChange={(e) => setDestinationToken(e.target.value)}
          className="px-3 py-2 rounded-lg bg-[#252830] text-white border border-white/20 focus:ring-2 focus:ring-teal-500/50 placeholder:text-[#A0A0A0]"
        />
        <label htmlFor="quote-source-chain" className="sr-only">Source chain ID</label>
        <input
          id="quote-source-chain"
          name="sourceChainId"
          type="text"
          placeholder="Source chain ID"
          value={sourceChainId}
          onChange={(e) => setSourceChainId(e.target.value)}
          className="px-3 py-2 rounded-lg bg-[#252830] text-white border border-white/20 focus:ring-2 focus:ring-teal-500/50 placeholder:text-[#A0A0A0]"
        />
        <label htmlFor="quote-destination-chain" className="sr-only">Destination chain ID</label>
        <input
          id="quote-destination-chain"
          name="destinationChainId"
          type="text"
          placeholder="Destination chain ID"
          value={destinationChainId}
          onChange={(e) => setDestinationChainId(e.target.value)}
          className="px-3 py-2 rounded-lg bg-[#252830] text-white border border-white/20 focus:ring-2 focus:ring-teal-500/50 placeholder:text-[#A0A0A0]"
        />
        <label htmlFor="quote-amount" className="sr-only">Amount (wei or decimal)</label>
        <input
          id="quote-amount"
          name="amount"
          type="text"
          placeholder="Amount (wei or decimal)"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
          className="px-3 py-2 rounded-lg bg-[#252830] text-white border border-white/20 focus:ring-2 focus:ring-teal-500/50 placeholder:text-[#A0A0A0] md:col-span-2"
        />
      </div>
      <button
        type="button"
        onClick={handleGetQuote}
        disabled={loading}
        className="px-4 py-2 rounded-lg bg-teal-600 text-white font-medium hover:bg-teal-500 disabled:opacity-50"
      >
        {loading ? 'Getting quote...' : 'Get full path quote'}
      </button>
      {error && <p className="mt-2 text-red-400 text-sm">{error}</p>}
      {quote && (
        <div className="mt-4 p-3 rounded-lg bg-white/5 text-sm text-white/90">
          <p><strong>Min received:</strong> {quote.minReceived ?? '—'}</p>
          {quote.sourceSwapQuote != null && <p><strong>Source swap quote:</strong> {quote.sourceSwapQuote}</p>}
          {quote.destinationSwapQuote != null && <p><strong>Destination swap quote:</strong> {quote.destinationSwapQuote}</p>}
          {quote.totalFee != null && <p><strong>Total fee:</strong> {quote.totalFee}</p>}
          {quote.estimatedTime != null && <p><strong>Estimated time:</strong> {quote.estimatedTime}s</p>}
        </div>
      )}
    </div>
  );
}
