'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';
import { ccApi, PaymentInfo, ChargeHistory } from '@/lib/api';
import SidebarLayout from '@/components/SidebarLayout';

export default function ChargePage() {
  const { t, language } = useTranslation();
  const { user } = useAuthStore();
  const router = useRouter();

  const [paymentInfo, setPaymentInfo] = useState<PaymentInfo | null>(null);
  const [ccBalance, setCcBalance] = useState<number>(0);
  const [chargeHistory, setChargeHistory] = useState<ChargeHistory[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  // Form state
  const [paymentMethod, setPaymentMethod] = useState<'usdc' | 'bank_transfer'>('usdc');
  const [amount, setAmount] = useState('');
  const [transactionHash, setTransactionHash] = useState('');
  const [walletAddress, setWalletAddress] = useState('');
  const [showSuccess, setShowSuccess] = useState(false);

  // Preset amounts
  const presetAmounts = [10, 20, 50, 100, 200, 500];

  useEffect(() => {
    if (!user) {
      router.push('/login');
      return;
    }
    loadData();
  }, [user, router]);

  const loadData = async () => {
    try {
      const [infoData, balanceData, historyData] = await Promise.all([
        ccApi.getPaymentInfo(),
        ccApi.getBalance(),
        ccApi.getChargeHistory(),
      ]);
      setPaymentInfo(infoData);
      setCcBalance(balanceData.cc_balance);
      setChargeHistory(historyData);
    } catch (error) {
      console.error('Failed to load data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const amountNum = parseInt(amount);
    if (!amountNum || amountNum < (paymentInfo?.min_charge_usd || 10)) {
      alert(`Minimum charge amount is ${paymentInfo?.min_charge_usd || 10} USD`);
      return;
    }

    if (paymentMethod === 'usdc' && !transactionHash) {
      alert('Please enter the transaction hash');
      return;
    }

    setSubmitting(true);
    try {
      if (paymentMethod === 'usdc') {
        await ccApi.chargeUSDC({
          amount_usdc: amountNum,
          transaction_hash: transactionHash,
          wallet_address: walletAddress,
          network: paymentInfo?.usdc_network || 'Polygon',
        });
      } else {
        await ccApi.chargeCC({
          amount: amountNum,
          currency: 'USD',
          payment_method: paymentMethod,
          wallet_address: walletAddress,
        });
      }
      setShowSuccess(true);
      setAmount('');
      setTransactionHash('');
      setWalletAddress('');
      loadData();
    } catch (error: any) {
      alert(error.response?.data?.detail || 'Failed to submit payment');
    } finally {
      setSubmitting(false);
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    alert(language === 'ko' ? '복사되었습니다!' : 'Copied to clipboard!');
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'completed':
        return <span className="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs">{language === 'ko' ? '완료' : 'Completed'}</span>;
      case 'pending':
        return <span className="px-2 py-1 bg-yellow-100 text-yellow-700 rounded-full text-xs">{language === 'ko' ? '대기' : 'Pending'}</span>;
      case 'rejected':
        return <span className="px-2 py-1 bg-red-100 text-red-700 rounded-full text-xs">{language === 'ko' ? '거부됨' : 'Rejected'}</span>;
      default:
        return <span className="px-2 py-1 bg-gray-100 text-gray-700 rounded-full text-xs">{status}</span>;
    }
  };

  if (!user) return null;

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500"></div>
      </div>
    );
  }

  return (
    <SidebarLayout groupKey="billing">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-800">{t.chargeTitle}</h1>
          <p className="text-gray-600 mt-2">{t.chargeSubtitle}</p>
        </div>

        {/* Balance Card */}
        <div className="bg-gradient-to-r from-primary-600 to-primary-700 rounded-xl p-6 text-white mb-8 shadow-lg">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-primary-100">{t.currentBalance}</p>
              <p className="text-4xl font-bold mt-2">{ccBalance.toLocaleString()} CC</p>
              <p className="text-primary-200 mt-2 text-sm">{paymentInfo?.rate}</p>
            </div>
            <div className="text-6xl opacity-50">💰</div>
          </div>
        </div>

        {showSuccess && (
          <div className="bg-green-50 border border-green-200 rounded-xl p-4 mb-8">
            <div className="flex items-center gap-3">
              <span className="text-2xl">✓</span>
              <div>
                <p className="font-semibold text-green-800">
                  {language === 'ko' ? '결제가 제출되었습니다!' : 'Payment Submitted Successfully!'}
                </p>
                <p className="text-sm text-green-600">
                  {language === 'ko' ? '결제 확인 후 CC가 충전됩니다.' : 'CC will be credited once verified.'}
                </p>
              </div>
            </div>
            <button onClick={() => setShowSuccess(false)} className="mt-3 text-sm text-green-700 hover:underline">
              {language === 'ko' ? '닫기' : 'Dismiss'}
            </button>
          </div>
        )}

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Payment Form */}
          <div className="bg-white rounded-xl shadow-lg p-6">
            <h2 className="text-xl font-semibold mb-4">{language === 'ko' ? '결제하기' : 'Make a Payment'}</h2>

            {/* Payment Method Selection */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                {language === 'ko' ? '결제 방법' : 'Payment Method'}
              </label>
              <div className="grid grid-cols-2 gap-3">
                <button
                  type="button"
                  onClick={() => setPaymentMethod('usdc')}
                  className={`p-4 border-2 rounded-lg text-left transition-colors ${
                    paymentMethod === 'usdc'
                      ? 'border-primary-500 bg-primary-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <div className="font-semibold">USDC</div>
                  <div className="text-xs text-gray-500">{language === 'ko' ? '암호화폐' : 'Cryptocurrency'}</div>
                </button>
                <button
                  type="button"
                  onClick={() => setPaymentMethod('bank_transfer')}
                  className={`p-4 border-2 rounded-lg text-left transition-colors ${
                    paymentMethod === 'bank_transfer'
                      ? 'border-primary-500 bg-primary-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <div className="font-semibold">{language === 'ko' ? '계좌이체' : 'Bank Transfer'}</div>
                  <div className="text-xs text-gray-500">{language === 'ko' ? '송금' : 'Wire Transfer'}</div>
                </button>
              </div>
            </div>

            {/* USDC Payment Info */}
            {paymentMethod === 'usdc' && paymentInfo && (
              <div className="mb-6 p-4 bg-blue-50 rounded-lg">
                <p className="text-sm font-medium text-blue-800 mb-2">
                  {language === 'ko' ? 'USDC를 아래 주소로 보내주세요:' : 'Send USDC to this address:'}
                </p>
                <div className="flex items-center gap-2">
                  <code className="flex-1 p-2 bg-white rounded text-xs break-all border">
                    {paymentInfo.usdc_wallet_address}
                  </code>
                  <button
                    type="button"
                    onClick={() => copyToClipboard(paymentInfo.usdc_wallet_address)}
                    className="px-3 py-2 bg-blue-500 text-white rounded text-sm hover:bg-blue-600"
                  >
                    {language === 'ko' ? '복사' : 'Copy'}
                  </button>
                </div>
                <p className="text-xs text-blue-600 mt-2">Network: {paymentInfo.usdc_network}</p>
              </div>
            )}

            {/* Bank Transfer Info */}
            {paymentMethod === 'bank_transfer' && (
              <div className="mb-6 p-4 bg-green-50 rounded-lg">
                <p className="text-sm font-medium text-green-800 mb-2">
                  {language === 'ko' ? '계좌 정보:' : 'Bank Account Info:'}
                </p>
                <div className="text-sm text-green-700 space-y-1">
                  <p>{language === 'ko' ? '은행: 신한은행' : 'Bank: Shinhan Bank'}</p>
                  <p>{language === 'ko' ? '계좌번호: 110-XXX-XXXXXX' : 'Account: 110-XXX-XXXXXX'}</p>
                  <p>{language === 'ko' ? '예금주: AutonetSellCar' : 'Name: AutonetSellCar'}</p>
                </div>
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-4">
              {/* Preset Amounts */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {language === 'ko' ? '금액 선택' : 'Select Amount'}
                </label>
                <div className="grid grid-cols-3 gap-2 mb-2">
                  {presetAmounts.map((preset) => (
                    <button
                      key={preset}
                      type="button"
                      onClick={() => setAmount(preset.toString())}
                      className={`py-2 px-3 border rounded-lg text-sm font-medium transition-colors ${
                        amount === preset.toString()
                          ? 'border-primary-500 bg-primary-50 text-primary-700'
                          : 'border-gray-200 hover:border-gray-300'
                      }`}
                    >
                      ${preset}
                    </button>
                  ))}
                </div>
                <input
                  type="number"
                  value={amount}
                  onChange={(e) => setAmount(e.target.value)}
                  min={paymentInfo?.min_charge_usd || 10}
                  max={paymentInfo?.max_charge_usd || 10000}
                  placeholder={`${language === 'ko' ? '직접 입력 (최소' : 'Enter amount (min'} $${paymentInfo?.min_charge_usd || 10})`}
                  className="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                  required
                />
                <p className="text-xs text-gray-500 mt-1">
                  {language === 'ko' ? `충전될 CC: ${amount || 0} CC` : `You will receive ${amount || 0} CC`}
                </p>
              </div>

              {paymentMethod === 'usdc' && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {language === 'ko' ? '트랜잭션 해시' : 'Transaction Hash'}
                  </label>
                  <input
                    type="text"
                    value={transactionHash}
                    onChange={(e) => setTransactionHash(e.target.value)}
                    placeholder="0x..."
                    className="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                    required
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    {language === 'ko' ? 'USDC 전송 후 트랜잭션 해시를 입력하세요' : 'Enter the transaction hash after sending USDC'}
                  </p>
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {language === 'ko' ? '지갑 주소 (환불용, 선택)' : 'Wallet Address (for refunds, optional)'}
                </label>
                <input
                  type="text"
                  value={walletAddress}
                  onChange={(e) => setWalletAddress(e.target.value)}
                  placeholder="0x..."
                  className="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                />
              </div>

              <button
                type="submit"
                disabled={submitting || !amount}
                className="w-full py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 font-semibold transition"
              >
                {submitting ? (language === 'ko' ? '제출 중...' : 'Submitting...') : (language === 'ko' ? '결제 제출' : 'Submit Payment')}
              </button>
            </form>
          </div>

          {/* Payment History */}
          <div className="bg-white rounded-xl shadow-lg p-6">
            <h2 className="text-xl font-semibold mb-4">{t.chargeHistory}</h2>

            {chargeHistory.length === 0 ? (
              <div className="text-center py-12 text-gray-500">
                <div className="text-4xl mb-2">📋</div>
                <p>{t.noChargeHistory}</p>
              </div>
            ) : (
              <div className="space-y-3 max-h-[500px] overflow-y-auto">
                {chargeHistory.map((payment) => (
                  <div key={payment.id} className="p-4 bg-gray-50 rounded-lg">
                    <div className="flex items-center justify-between mb-2">
                      <span className="font-semibold">
                        {payment.amount} {payment.currency}
                      </span>
                      {getStatusBadge(payment.status)}
                    </div>
                    <div className="text-sm text-gray-600">
                      <div>CC: +{payment.cc_amount}</div>
                      <div>{language === 'ko' ? '방법' : 'Method'}: {payment.payment_method}</div>
                      {payment.transaction_id && (
                        <div className="truncate text-xs">TX: {payment.transaction_id}</div>
                      )}
                      <div className="text-xs text-gray-400 mt-1">
                        {payment.created_at ? new Date(payment.created_at).toLocaleString() : '-'}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Instructions */}
        <div className="mt-8 bg-white rounded-xl shadow-lg p-6">
          <h2 className="text-lg font-semibold mb-4">{language === 'ko' ? 'CC 충전 방법' : 'How to Charge CC'}</h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div className="flex gap-4">
              <div className="w-8 h-8 bg-primary-100 text-primary-600 rounded-full flex items-center justify-center font-bold flex-shrink-0">1</div>
              <div>
                <p className="font-medium">{language === 'ko' ? '결제 방법 선택' : 'Choose Payment Method'}</p>
                <p className="text-sm text-gray-500">{language === 'ko' ? 'USDC 또는 계좌이체' : 'Select USDC or Bank Transfer'}</p>
              </div>
            </div>
            <div className="flex gap-4">
              <div className="w-8 h-8 bg-primary-100 text-primary-600 rounded-full flex items-center justify-center font-bold flex-shrink-0">2</div>
              <div>
                <p className="font-medium">{language === 'ko' ? '결제 진행' : 'Send Payment'}</p>
                <p className="text-sm text-gray-500">{language === 'ko' ? '표시된 주소/계좌로 송금' : 'Transfer to our account/wallet'}</p>
              </div>
            </div>
            <div className="flex gap-4">
              <div className="w-8 h-8 bg-primary-100 text-primary-600 rounded-full flex items-center justify-center font-bold flex-shrink-0">3</div>
              <div>
                <p className="font-medium">{language === 'ko' ? '제출 후 대기' : 'Submit & Wait'}</p>
                <p className="text-sm text-gray-500">{language === 'ko' ? '확인 후 CC 충전' : 'CC credited after verification'}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </SidebarLayout>
  );
}
