'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useAuthStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

interface DealerInfo {
  id: number;
  user_id: number;
  dealer_code: string;
  dealer_card_url: string | null;
  business_name: string;
  real_name: string;
  phone: string;
  photo_url: string | null;
  bank_name: string;
  bank_account: string;
  account_holder: string;
  total_commission_earned: number;
  total_withdrawn: number;
  pending_withdrawal: number;
  is_active: boolean;
  created_at: string;
}

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

  const [loading, setLoading] = useState(true);
  const [dealerInfo, setDealerInfo] = useState<DealerInfo | null>(null);

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

    if (!user.is_dealer) {
      router.push('/dealer/apply');
      return;
    }

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

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

    try {
      const response = await fetch(`${API_BASE_URL}/api/dealer/my-info`, {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (response.ok) {
        const data = await response.json();
        setDealerInfo(data);
      }
    } catch (error) {
      console.error('Failed to fetch dealer info:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('ko-KR').format(amount);
  };

  if (!user || 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>
    );
  }

  if (!dealerInfo) {
    return (
      <div className="min-h-screen bg-gray-50 py-12">
        <div className="container mx-auto px-4">
          <div className="max-w-2xl mx-auto text-center">
            <div className="text-6xl mb-4">❌</div>
            <h1 className="text-2xl font-bold text-gray-800 mb-4">
              {language === 'ko' ? '딜러 정보를 찾을 수 없습니다' : 'Dealer info not found'}
            </h1>
            <Link
              href="/dealer/apply"
              className="inline-block px-6 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition"
            >
              {t.becomeDealer}
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="container mx-auto px-4">
        <div className="max-w-2xl mx-auto">
          {/* Header */}
          <div className="text-center mb-8">
            <h1 className="text-3xl font-bold text-gray-800 mb-2">{t.myDealerCard}</h1>
            <p className="text-gray-600">
              {dealerInfo.is_active ? (
                <span className="inline-flex items-center gap-1 text-green-600">
                  <span className="w-2 h-2 bg-green-500 rounded-full"></span>
                  {t.active}
                </span>
              ) : (
                <span className="inline-flex items-center gap-1 text-red-600">
                  <span className="w-2 h-2 bg-red-500 rounded-full"></span>
                  {t.inactive}
                </span>
              )}
            </p>
          </div>

          {/* Dealer Card */}
          <div className="bg-gradient-to-br from-gray-800 to-gray-900 text-white rounded-2xl p-6 mb-6 shadow-xl relative overflow-hidden">
            {/* Background Pattern */}
            <div className="absolute top-0 right-0 w-64 h-64 bg-white/5 rounded-full -translate-y-1/2 translate-x-1/2"></div>
            <div className="absolute bottom-0 left-0 w-32 h-32 bg-white/5 rounded-full translate-y-1/2 -translate-x-1/2"></div>

            <div className="relative">
              {/* Header */}
              <div className="flex items-center justify-between mb-6">
                <div>
                  <p className="text-gray-400 text-sm">AutonetSellCar</p>
                  <p className="text-lg font-semibold">DEALER CARD</p>
                </div>
                <div className="text-right">
                  <p className="text-gray-400 text-xs">{t.dealerCode}</p>
                  <p className="text-2xl font-mono font-bold tracking-wider">{dealerInfo.dealer_code}</p>
                </div>
              </div>

              {/* Info */}
              <div className="flex items-end justify-between">
                <div>
                  <p className="text-gray-400 text-xs mb-1">{t.businessName}</p>
                  <p className="text-xl font-semibold mb-4">{dealerInfo.business_name}</p>

                  <p className="text-gray-400 text-xs mb-1">{t.realName}</p>
                  <p className="font-medium">{dealerInfo.real_name}</p>
                </div>

                {/* Photo placeholder */}
                <div className="w-20 h-24 bg-gray-700 rounded-lg flex items-center justify-center border-2 border-gray-600">
                  {dealerInfo.photo_url ? (
                    <img src={dealerInfo.photo_url} alt="Photo" className="w-full h-full object-cover rounded-lg" />
                  ) : (
                    <span className="text-3xl">👤</span>
                  )}
                </div>
              </div>

              {/* Footer */}
              <div className="mt-6 pt-4 border-t border-gray-700">
                <p className="text-gray-400 text-xs">
                  {language === 'ko' ? '발급일: ' : 'Issued: '}
                  {new Date(dealerInfo.created_at).toLocaleDateString()}
                </p>
              </div>
            </div>
          </div>

          {/* Earnings Summary */}
          <div className="bg-white rounded-xl shadow-lg p-6 mb-6">
            <h2 className="text-xl font-semibold text-gray-800 mb-4">
              {language === 'ko' ? '수익 현황' : 'Earnings Summary'}
            </h2>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                <p className="text-sm text-green-600">{t.totalCommission}</p>
                <p className="text-2xl font-bold text-green-700">
                  {formatCurrency(dealerInfo.total_commission_earned)} {language === 'ko' ? '원' : 'KRW'}
                </p>
              </div>

              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <p className="text-sm text-blue-600">{t.totalWithdrawn}</p>
                <p className="text-2xl font-bold text-blue-700">
                  {formatCurrency(dealerInfo.total_withdrawn)} {language === 'ko' ? '원' : 'KRW'}
                </p>
              </div>

              <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                <p className="text-sm text-yellow-600">{t.pendingWithdrawal}</p>
                <p className="text-2xl font-bold text-yellow-700">
                  {formatCurrency(dealerInfo.pending_withdrawal)} {language === 'ko' ? '원' : 'KRW'}
                </p>
              </div>
            </div>

            {/* Available Balance */}
            <div className="mt-4 p-4 bg-gray-50 rounded-lg">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600">
                    {language === 'ko' ? '출금 가능 잔액' : 'Available for Withdrawal'}
                  </p>
                  <p className="text-2xl font-bold text-gray-800">
                    {formatCurrency(
                      dealerInfo.total_commission_earned - dealerInfo.total_withdrawn - dealerInfo.pending_withdrawal
                    )} {language === 'ko' ? '원' : 'KRW'}
                  </p>
                </div>
                <Link
                  href="/withdrawal"
                  className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition"
                >
                  {language === 'ko' ? '출금 신청' : 'Request Withdrawal'}
                </Link>
              </div>
            </div>
          </div>

          {/* Bank Account Info */}
          <div className="bg-white rounded-xl shadow-lg p-6">
            <h2 className="text-xl font-semibold text-gray-800 mb-4">
              {language === 'ko' ? '출금 계좌 정보' : 'Withdrawal Bank Account'}
            </h2>

            <div className="space-y-3">
              <div className="flex justify-between py-2 border-b border-gray-100">
                <span className="text-gray-600">{t.bankName}</span>
                <span className="font-medium">{dealerInfo.bank_name}</span>
              </div>
              <div className="flex justify-between py-2 border-b border-gray-100">
                <span className="text-gray-600">{t.bankAccount}</span>
                <span className="font-medium font-mono">{dealerInfo.bank_account}</span>
              </div>
              <div className="flex justify-between py-2">
                <span className="text-gray-600">{t.accountHolder}</span>
                <span className="font-medium">{dealerInfo.account_holder}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
