'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';
import { withdrawalApi, WithdrawalBalance, WithdrawalRequest } from '@/lib/api';
import SidebarLayout from '@/components/SidebarLayout';

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

  const [balance, setBalance] = useState<WithdrawalBalance | null>(null);
  const [requests, setRequests] = useState<WithdrawalRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // Form state
  const [amount, setAmount] = useState('');
  const [bankName, setBankName] = useState('');
  const [bankAccount, setBankAccount] = useState('');
  const [accountHolder, setAccountHolder] = useState('');

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

    fetchData();
  }, [user, router]);

  const fetchData = async () => {
    if (!token) return;

    try {
      const [balanceData, requestsData] = await Promise.all([
        withdrawalApi.getBalance(),
        withdrawalApi.getMyRequests(),
      ]);

      setBalance(balanceData);
      setRequests(requestsData);
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!balance) return;

    const amountNum = parseFloat(amount);
    if (isNaN(amountNum) || amountNum <= 0) {
      setMessage({ type: 'error', text: language === 'ko' ? '유효한 금액을 입력해주세요' : 'Please enter a valid amount' });
      return;
    }

    if (amountNum < 10) {
      setMessage({ type: 'error', text: t.minWithdrawal });
      return;
    }

    if (amountNum > balance.available_balance) {
      setMessage({ type: 'error', text: language === 'ko' ? '잔액이 부족합니다' : 'Insufficient balance' });
      return;
    }

    setSubmitting(true);
    setMessage(null);

    try {
      await withdrawalApi.createRequest({
        amount: amountNum,
        bank_name: bankName,
        bank_account: bankAccount,
        account_holder: accountHolder,
      });

      setMessage({ type: 'success', text: t.withdrawalRequested });
      setShowForm(false);
      setAmount('');
      setBankName('');
      setBankAccount('');
      setAccountHolder('');

      // Refresh data
      fetchData();
    } catch (error: any) {
      const errorMsg = error.response?.data?.detail || t.withdrawalFailed;
      setMessage({ type: 'error', text: errorMsg });
    } finally {
      setSubmitting(false);
    }
  };

  const formatPrice = (price: number) => {
    return new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(price);
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'pending':
        return <span className="px-2 py-1 bg-yellow-100 text-yellow-700 rounded text-xs">{t.withdrawalPending}</span>;
      case 'approved':
        return <span className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">{t.withdrawalApproved}</span>;
      case 'completed':
        return <span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs">{t.withdrawalCompleted}</span>;
      case 'rejected':
        return <span className="px-2 py-1 bg-red-100 text-red-700 rounded text-xs">{t.withdrawalRejected}</span>;
      default:
        return <span className="px-2 py-1 bg-gray-100 text-gray-700 rounded text-xs">{status}</span>;
    }
  };

  const calculateNetAmount = (amt: string) => {
    const amountNum = parseFloat(amt);
    if (isNaN(amountNum) || amountNum <= 0) return 0;
    const tax = amountNum * 0.033;
    return amountNum - tax;
  };

  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-600"></div>
      </div>
    );
  }

  return (
    <SidebarLayout groupKey="billing">
      <div className="container mx-auto">
        <div className="max-w-2xl mx-auto">
          {/* Header */}
          <div className="mb-6">
            <h1 className="text-2xl font-bold text-gray-800">{t.withdrawal}</h1>
            <p className="text-gray-600">{t.withdrawalRequest}</p>
          </div>

          {/* Balance Card */}
          {balance && (
            <div className="bg-gradient-to-r from-primary-600 to-primary-700 text-white rounded-xl p-6 mb-6">
              <h2 className="text-lg font-semibold mb-4">{t.availableBalance}</h2>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-primary-100 text-sm">{language === 'ko' ? '총 수익' : 'Total Earned'}</p>
                  <p className="text-xl font-bold">${formatPrice(balance.total_earned)}</p>
                </div>
                <div>
                  <p className="text-primary-100 text-sm">{t.availableBalance}</p>
                  <p className="text-2xl font-bold">${formatPrice(balance.available_balance)}</p>
                </div>
                <div>
                  <p className="text-primary-100 text-sm">{language === 'ko' ? '출금 완료' : 'Withdrawn'}</p>
                  <p className="text-xl font-bold">${formatPrice(balance.total_withdrawn)}</p>
                </div>
                <div>
                  <p className="text-primary-100 text-sm">{language === 'ko' ? '대기 중' : 'Pending'}</p>
                  <p className="text-xl font-bold">${formatPrice(balance.pending_withdrawal)}</p>
                </div>
              </div>
            </div>
          )}

          {/* Message */}
          {message && (
            <div className={`p-4 rounded-lg mb-6 ${
              message.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
            }`}>
              {message.text}
            </div>
          )}

          {/* Withdrawal Form */}
          {!showForm ? (
            <button
              onClick={() => setShowForm(true)}
              disabled={!balance || balance.available_balance < 10}
              className={`w-full py-4 rounded-xl font-semibold transition mb-6 ${
                balance && balance.available_balance >= 10
                  ? 'bg-primary-600 text-white hover:bg-primary-700'
                  : 'bg-gray-300 text-gray-500 cursor-not-allowed'
              }`}
            >
              {t.requestWithdrawal}
            </button>
          ) : (
            <div className="bg-white rounded-xl shadow p-6 mb-6">
              <h3 className="text-lg font-semibold mb-4">{t.withdrawalRequest}</h3>
              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t.withdrawalAmount}
                  </label>
                  <input
                    type="number"
                    value={amount}
                    onChange={(e) => setAmount(e.target.value)}
                    placeholder="0"
                    className="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                    required
                    min="10"
                    step="0.01"
                    max={balance?.available_balance || 0}
                  />
                  <p className="text-xs text-gray-500 mt-1">{t.minWithdrawal}</p>
                  {amount && parseFloat(amount) > 0 && (
                    <div className="mt-2 p-3 bg-gray-50 rounded-lg text-sm">
                      <div className="flex justify-between">
                        <span className="text-gray-600">{t.withdrawalAmount}</span>
                        <span>${formatPrice(parseFloat(amount))}</span>
                      </div>
                      <div className="flex justify-between text-red-600">
                        <span>{t.taxWithheld}</span>
                        <span>-${formatPrice(parseFloat(amount) * 0.033)}</span>
                      </div>
                      <div className="flex justify-between font-bold mt-2 pt-2 border-t">
                        <span>{t.netAmount}</span>
                        <span className="text-primary-600">${formatPrice(calculateNetAmount(amount))}</span>
                      </div>
                    </div>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t.bankName}
                  </label>
                  <input
                    type="text"
                    value={bankName}
                    onChange={(e) => setBankName(e.target.value)}
                    placeholder={language === 'ko' ? '국민은행' : 'Bank Name'}
                    className="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t.bankAccount}
                  </label>
                  <input
                    type="text"
                    value={bankAccount}
                    onChange={(e) => setBankAccount(e.target.value)}
                    placeholder={language === 'ko' ? '계좌번호 입력' : 'Account Number'}
                    className="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t.accountHolder}
                  </label>
                  <input
                    type="text"
                    value={accountHolder}
                    onChange={(e) => setAccountHolder(e.target.value)}
                    placeholder={language === 'ko' ? '예금주명' : 'Account Holder Name'}
                    className="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                    required
                  />
                </div>

                <div className="flex gap-3 pt-4">
                  <button
                    type="button"
                    onClick={() => setShowForm(false)}
                    className="flex-1 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition"
                  >
                    {language === 'ko' ? '취소' : 'Cancel'}
                  </button>
                  <button
                    type="submit"
                    disabled={submitting}
                    className="flex-1 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition disabled:opacity-50"
                  >
                    {submitting ? t.loading : t.requestWithdrawal}
                  </button>
                </div>
              </form>
            </div>
          )}

          {/* Info Card */}
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
            <div className="flex items-start gap-3">
              <span className="text-2xl">💡</span>
              <div className="text-sm text-blue-700">
                <p className="font-medium mb-1">{language === 'ko' ? '출금 안내' : 'Withdrawal Info'}</p>
                <ul className="list-disc list-inside space-y-1">
                  <li>{t.minWithdrawal}</li>
                  <li>{language === 'ko' ? '원천징수 3.3%가 적용됩니다' : '3.3% tax withholding applies'}</li>
                  <li>{language === 'ko' ? '출금은 영업일 기준 2-3일 내 처리됩니다' : 'Withdrawals are processed within 2-3 business days'}</li>
                </ul>
              </div>
            </div>
          </div>

          {/* Withdrawal History */}
          <div>
            <h2 className="text-lg font-semibold mb-4">{t.withdrawalHistory}</h2>
            {requests.length > 0 ? (
              <div className="space-y-4">
                {requests.map((request) => (
                  <div key={request.id} className="bg-white rounded-xl shadow p-4">
                    <div className="flex items-center justify-between mb-3">
                      <span className="text-lg">💸</span>
                      {getStatusBadge(request.status)}
                    </div>

                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                      <div>
                        <p className="text-gray-500">{t.withdrawalAmount}</p>
                        <p className="font-medium">${formatPrice(request.amount)}</p>
                      </div>
                      <div>
                        <p className="text-gray-500">{t.taxWithheld}</p>
                        <p className="font-medium text-red-600">-${formatPrice(request.tax_withheld)}</p>
                      </div>
                      <div>
                        <p className="text-gray-500">{t.netAmount}</p>
                        <p className="font-bold text-primary-600">${formatPrice(request.net_amount)}</p>
                      </div>
                      <div>
                        <p className="text-gray-500">{t.bankName}</p>
                        <p className="font-medium">{request.bank_name}</p>
                      </div>
                    </div>

                    {request.admin_note && (
                      <div className="mt-3 p-2 bg-gray-50 rounded text-sm">
                        <p className="text-gray-600">{request.admin_note}</p>
                      </div>
                    )}

                    <div className="mt-3 pt-3 border-t flex justify-between text-xs text-gray-500">
                      <span>{language === 'ko' ? '신청일' : 'Requested'}: {new Date(request.requested_at).toLocaleDateString()}</span>
                      {request.processed_at && (
                        <span>{language === 'ko' ? '처리일' : 'Processed'}: {new Date(request.processed_at).toLocaleDateString()}</span>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="bg-white rounded-xl shadow p-8 text-center">
                <div className="text-4xl mb-4">💸</div>
                <p className="text-gray-500">{t.noWithdrawalHistory}</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </SidebarLayout>
  );
}
