'use client';

import { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { ArrowDownUp, ChevronDown } from 'lucide-react';
import { useAccount } from 'wagmi';
import { useTokenDetails, useGetPoolsByToken, type TokenDetails } from '@/hooks/usePartyPlanner';
import { formatUnits } from 'viem';

export function SwapForm() {
  const { t } = useTranslation();
  const { isConnected, address } = useAccount();
  const [fromAmount, setFromAmount] = useState('');
  const [toAmount, setToAmount] = useState('');
  const [selectedFromToken, setSelectedFromToken] = useState<TokenDetails | null>(null);
  const [selectedToToken, setSelectedToToken] = useState<TokenDetails | null>(null);
  const [isFromDropdownOpen, setIsFromDropdownOpen] = useState(false);
  const [isToDropdownOpen, setIsToDropdownOpen] = useState(false);
  const [slippage, setSlippage] = useState<number>(0.5); // Default 0.5%
  const [customSlippage, setCustomSlippage] = useState<string>('');
  const [isCustomSlippage, setIsCustomSlippage] = useState(false);
  const fromDropdownRef = useRef<HTMLDivElement>(null);
  const toDropdownRef = useRef<HTMLDivElement>(null);

  // Use the custom hook to get all token details with a single batched RPC call
  const { tokenDetails, loading, error } = useTokenDetails(address);

  // Get available tokens for the selected "from" token
  const { availableTokens } = useGetPoolsByToken(selectedFromToken?.address);

  // Trigger the hook to fetch data when address is available
  useEffect(() => {
    if (tokenDetails) {
      console.log('Token details loaded in swap-form');
    }
  }, [tokenDetails]);

  // Close dropdowns when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (fromDropdownRef.current && !fromDropdownRef.current.contains(event.target as Node)) {
        setIsFromDropdownOpen(false);
      }
      if (toDropdownRef.current && !toDropdownRef.current.contains(event.target as Node)) {
        setIsToDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Calculate and log limit price when amount or slippage changes
  useEffect(() => {
    if (fromAmount && parseFloat(fromAmount) > 0) {
      const amount = parseFloat(fromAmount);
      const slippagePercent = isCustomSlippage ? parseFloat(customSlippage) || 0 : slippage;
      const limitPrice = amount * (1 + slippagePercent / 100);
      console.log('Limit Price:', limitPrice);
      console.log('From Amount:', amount);
      console.log('Slippage %:', slippagePercent);
      console.log('Additional Amount from Slippage:', limitPrice - amount);
    }
  }, [fromAmount, slippage, customSlippage, isCustomSlippage]);

  const handleSwap = () => {
    // Swap logic will be implemented later
    console.log('Swap clicked');
  };

  const switchTokens = () => {
    // Switch tokens logic
    setFromAmount(toAmount);
    setToAmount(fromAmount);
  };

  return (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader>
        <CardTitle>{t('swap.title')}</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* From Token */}
        <div className="space-y-2">
          <div className="flex justify-between text-sm">
            <label className="text-muted-foreground">{t('swap.youPay')}</label>
            <span className="text-muted-foreground">
              {t('swap.balance')}: {selectedFromToken ? formatUnits(selectedFromToken.balance, selectedFromToken.decimals) : '0.00'}
            </span>
          </div>
          <div className="flex gap-2">
            <Input
              type="number"
              placeholder="0.0"
              value={fromAmount}
              onChange={(e) => setFromAmount(e.target.value)}
              className="text-2xl h-16"
            />
            <div className="relative min-w-[160px]" ref={fromDropdownRef}>
              <Button
                variant="secondary"
                className="w-full h-16 justify-between"
                onClick={() => setIsFromDropdownOpen(!isFromDropdownOpen)}
              >
                {selectedFromToken ? (
                  <span className="font-medium">{selectedFromToken.symbol}</span>
                ) : (
                  t('swap.selectToken')
                )}
                <ChevronDown className="h-4 w-4 ml-2" />
              </Button>
              {isFromDropdownOpen && (
                <div className="absolute z-50 w-full mt-2 bg-popover border rounded-md shadow-lg max-h-[300px] overflow-y-auto">
                  {tokenDetails && tokenDetails.length > 0 ? (
                    tokenDetails.map((token) => (
                      <button
                        key={token.address}
                        className="w-full px-4 py-3 text-left hover:bg-accent focus:bg-accent focus:outline-none flex items-center justify-between"
                        onClick={() => {
                          setSelectedFromToken(token);
                          setIsFromDropdownOpen(false);
                        }}
                      >
                        <span className="font-medium">{token.symbol}</span>
                        <span className="text-sm text-muted-foreground">
                          {formatUnits(token.balance, token.decimals)}
                        </span>
                      </button>
                    ))
                  ) : (
                    <div className="px-4 py-3 text-sm text-muted-foreground">
                      {loading ? 'Loading tokens...' : 'No tokens available'}
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Switch Button */}
        <div className="flex justify-center">
          <Button
            variant="ghost"
            size="icon"
            onClick={switchTokens}
            className="rounded-full"
          >
            <ArrowDownUp className="h-4 w-4" />
          </Button>
        </div>

        {/* To Token */}
        <div className="space-y-2">
          <div className="flex justify-between text-sm">
            <label className="text-muted-foreground">{t('swap.youReceive')}</label>
            <span className="text-muted-foreground">
              {t('swap.balance')}: {selectedToToken ? formatUnits(selectedToToken.balance, selectedToToken.decimals) : '0.00'}
            </span>
          </div>
          <div className="flex gap-2">
            <Input
              type="number"
              placeholder="0.0"
              value={toAmount}
              onChange={(e) => setToAmount(e.target.value)}
              className="text-2xl h-16"
              disabled={!selectedFromToken}
            />
            <div className="relative min-w-[160px]" ref={toDropdownRef}>
              <Button
                variant="secondary"
                className="w-full h-16 justify-between"
                onClick={() => setIsToDropdownOpen(!isToDropdownOpen)}
                disabled={!selectedFromToken}
              >
                {selectedToToken ? (
                  <span className="font-medium">{selectedToToken.symbol}</span>
                ) : (
                  t('swap.selectToken')
                )}
                <ChevronDown className="h-4 w-4 ml-2" />
              </Button>
              {isToDropdownOpen && (
                <div className="absolute z-50 w-full mt-2 bg-popover border rounded-md shadow-lg max-h-[300px] overflow-y-auto">
                  {availableTokens && availableTokens.length > 0 && tokenDetails ? (
                    // Filter tokenDetails to only show tokens in availableTokens
                    tokenDetails
                      .filter((token) =>
                        availableTokens.some((availToken) =>
                          availToken.toLowerCase() === token.address.toLowerCase()
                        )
                      )
                      .map((token) => (
                        <button
                          key={token.address}
                          className="w-full px-4 py-3 text-left hover:bg-accent focus:bg-accent focus:outline-none flex items-center justify-between"
                          onClick={() => {
                            setSelectedToToken(token);
                            setIsToDropdownOpen(false);
                          }}
                        >
                          <span className="font-medium">{token.symbol}</span>
                          <span className="text-sm text-muted-foreground">
                            {formatUnits(token.balance, token.decimals)}
                          </span>
                        </button>
                      ))
                  ) : selectedFromToken ? (
                    <div className="px-4 py-3 text-sm text-muted-foreground">
                      {loading ? 'Loading available tokens...' : 'No tokens available for swap'}
                    </div>
                  ) : (
                    <div className="px-4 py-3 text-sm text-muted-foreground">
                      Select a token in "You Pay" first
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Slippage Tolerance */}
        <div className="space-y-3 pt-2">
          <div className="flex justify-between items-center">
            <label className="text-sm font-medium">Slippage Tolerance</label>
            <span className="text-sm text-muted-foreground">
              {isCustomSlippage ? customSlippage || '0' : slippage}%
            </span>
          </div>
          <div className="flex gap-2 flex-wrap">
            {[0.1, 0.2, 0.3, 1, 2, 3].map((percent) => (
              <Button
                key={percent}
                variant={!isCustomSlippage && slippage === percent ? 'default' : 'outline'}
                size="sm"
                onClick={() => {
                  setSlippage(percent);
                  setIsCustomSlippage(false);
                }}
                className="flex-1 min-w-[60px]"
              >
                {percent}%
              </Button>
            ))}
            <div className="flex-1 min-w-[80px] relative">
              <Input
                type="number"
                placeholder="Custom"
                value={customSlippage}
                onChange={(e) => {
                  setCustomSlippage(e.target.value);
                  setIsCustomSlippage(true);
                }}
                onFocus={() => setIsCustomSlippage(true)}
                className={`h-9 pr-6 ${isCustomSlippage ? 'border-primary' : ''}`}
                step="0.01"
              />
              {isCustomSlippage && (
                <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
                  %
                </span>
              )}
            </div>
          </div>
        </div>

        {/* Swap Button */}
        <Button
          className="w-full h-14 text-lg"
          onClick={handleSwap}
          disabled={!isConnected || !fromAmount || !toAmount}
        >
          {!isConnected ? t('swap.connectWalletToSwap') : t('swap.swapButton')}
        </Button>
      </CardContent>
    </Card>
  );
}
