'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 || '';

interface DealerApplication {
  id: number;
  user_id: number;
  business_name: string;
  business_number: string | null;
  real_name: string;
  phone: string;
  bank_name: string;
  bank_account: string;
  account_holder: string;
  photo_url: string | null;
  status: string;
  rejected_reason: string | null;
  applied_at: string;
  approved_at: string | null;
}

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

  const [loading, setLoading] = useState(false);
  const [checkingApplication, setCheckingApplication] = useState(true);
  const [existingApplication, setExistingApplication] = useState<DealerApplication | null>(null);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  const [step, setStep] = useState<'agreement' | 'form'>('agreement');
  const [privacyAgreed, setPrivacyAgreed] = useState(false);
  const [obligationAgreed, setObligationAgreed] = useState(false);
  const [agreeError, setAgreeError] = useState(false);

  const [formData, setFormData] = useState({
    business_name: '',
    business_number: '',
    real_name: '',
    id_number: '',
    phone: '',
    bank_name: '',
    bank_account: '',
    account_holder: '',
    photo_url: '',
  });

  useEffect(() => {
    if (isLoading) return;

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

    if (user.is_dealer) {
      router.push('/dealer/my-card');
      return;
    }

    // Check for existing application
    checkExistingApplication();
  }, [user, router, isLoading]);

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

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

      if (response.ok) {
        const data = await response.json();
        setExistingApplication(data);
      }
    } catch (error) {
      // No existing application
    } finally {
      setCheckingApplication(false);
    }
  };

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

    setLoading(true);
    setMessage(null);

    try {
      const response = await fetch(`${API_BASE_URL}/api/dealer/apply`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(formData),
      });

      if (response.ok) {
        const data = await response.json();
        setExistingApplication(data);
        setMessage({ type: 'success', text: t.applicationSubmitted });
      } else {
        const error = await response.json();
        setMessage({ type: 'error', text: error.detail || t.applicationFailed });
      }
    } catch (error) {
      console.error('Application failed:', error);
      setMessage({ type: 'error', text: t.applicationFailed });
    } finally {
      setLoading(false);
    }
  };

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

  // Show existing application status
  if (existingApplication) {
    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">
            <div className="text-center mb-8">
              <h1 className="text-3xl font-bold text-gray-800 mb-2">{t.dealerApplication}</h1>
            </div>

            <div className="bg-white rounded-xl shadow-lg p-6">
              {existingApplication.status === 'pending' && (
                <div className="text-center">
                  <div className="text-6xl mb-4">⏳</div>
                  <h2 className="text-xl font-semibold text-yellow-600 mb-2">{t.applicationPending}</h2>
                  <p className="text-gray-600 mb-4">{t.pendingApplicationMessage}</p>
                  <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 text-left">
                    <p className="text-sm text-yellow-700">
                      {language === 'ko' ? '신청일: ' : 'Applied: '}
                      {new Date(existingApplication.applied_at).toLocaleDateString()}
                    </p>
                  </div>
                </div>
              )}

              {existingApplication.status === 'approved' && (
                <div className="text-center">
                  <div className="text-6xl mb-4">✅</div>
                  <h2 className="text-xl font-semibold text-green-600 mb-2">{t.applicationApproved}</h2>
                  <Link
                    href="/dealer/my-card"
                    className="inline-block mt-4 px-6 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition"
                  >
                    {t.myDealerCard}
                  </Link>
                </div>
              )}

              {existingApplication.status === 'rejected' && (
                <div className="text-center">
                  <div className="text-6xl mb-4">❌</div>
                  <h2 className="text-xl font-semibold text-red-600 mb-2">{t.applicationRejected}</h2>
                  <p className="text-gray-600 mb-4">{t.rejectedApplicationMessage}</p>
                  {existingApplication.rejected_reason && (
                    <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-left">
                      <p className="text-sm font-medium text-red-700">{t.rejectReason}:</p>
                      <p className="text-sm text-red-600">{existingApplication.rejected_reason}</p>
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }

  const handleProceedToForm = () => {
    if (!privacyAgreed || !obligationAgreed) {
      setAgreeError(true);
      return;
    }
    setAgreeError(false);
    setStep('form');
  };

  const handleAgreeAll = (checked: boolean) => {
    setPrivacyAgreed(checked);
    setObligationAgreed(checked);
    if (checked) setAgreeError(false);
  };

  // Step 1: Agreement
  if (step === 'agreement') {
    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.dealerAgreementTitle}</h1>
              <p className="text-gray-600">{t.dealerApplicationSubtitle}</p>
            </div>

            {/* Benefits Card */}
            <div className="bg-gradient-to-r from-primary-600 to-primary-700 text-white rounded-xl p-6 mb-8">
              <h2 className="text-xl font-semibold mb-4">
                {language === 'ko' ? '딜러 혜택' : 'Dealer Benefits'}
              </h2>
              <ul className="space-y-2">
                <li className="flex items-center gap-2">
                  <span>💰</span>
                  <span>{language === 'ko' ? '차량 판매 시 수수료 50% 수익' : '50% commission on vehicle sales'}</span>
                </li>
                <li className="flex items-center gap-2">
                  <span>🎫</span>
                  <span>{language === 'ko' ? '공식 딜러증 발급' : 'Official dealer card issued'}</span>
                </li>
                <li className="flex items-center gap-2">
                  <span>📈</span>
                  <span>{language === 'ko' ? '수익 관리 대시보드' : 'Earnings management dashboard'}</span>
                </li>
              </ul>
            </div>

            {/* Privacy Agreement */}
            <div className="bg-white rounded-xl shadow-lg p-6 mb-4">
              <div className="flex items-start gap-3 mb-3">
                <input
                  type="checkbox"
                  id="privacy-agree"
                  checked={privacyAgreed}
                  onChange={(e) => {
                    setPrivacyAgreed(e.target.checked);
                    if (e.target.checked) setAgreeError(false);
                  }}
                  className="mt-1 w-5 h-5 text-primary-600 rounded border-gray-300 focus:ring-primary-500 cursor-pointer"
                />
                <label htmlFor="privacy-agree" className="font-semibold text-gray-800 cursor-pointer">
                  {t.dealerPrivacyAgreement}
                </label>
              </div>
              <div className="bg-gray-50 border border-gray-200 rounded-lg p-4 max-h-48 overflow-y-auto">
                <p className="text-sm text-gray-700 whitespace-pre-line leading-relaxed">
                  {t.dealerPrivacyContent}
                </p>
              </div>
            </div>

            {/* Obligation Agreement */}
            <div className="bg-white rounded-xl shadow-lg p-6 mb-4">
              <div className="flex items-start gap-3 mb-3">
                <input
                  type="checkbox"
                  id="obligation-agree"
                  checked={obligationAgreed}
                  onChange={(e) => {
                    setObligationAgreed(e.target.checked);
                    if (e.target.checked) setAgreeError(false);
                  }}
                  className="mt-1 w-5 h-5 text-primary-600 rounded border-gray-300 focus:ring-primary-500 cursor-pointer"
                />
                <label htmlFor="obligation-agree" className="font-semibold text-gray-800 cursor-pointer">
                  {t.dealerObligationAgreement}
                </label>
              </div>
              <div className="bg-gray-50 border border-gray-200 rounded-lg p-4 max-h-48 overflow-y-auto">
                <p className="text-sm text-gray-700 whitespace-pre-line leading-relaxed">
                  {t.dealerObligationContent}
                </p>
              </div>
            </div>

            {/* Agree All + Proceed */}
            <div className="bg-white rounded-xl shadow-lg p-6">
              <label className="flex items-center gap-3 cursor-pointer mb-4">
                <input
                  type="checkbox"
                  checked={privacyAgreed && obligationAgreed}
                  onChange={(e) => handleAgreeAll(e.target.checked)}
                  className="w-5 h-5 text-primary-600 rounded border-gray-300 focus:ring-primary-500"
                />
                <span className="font-semibold text-gray-800">{t.dealerAgreeAll}</span>
              </label>

              {agreeError && (
                <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
                  <p className="text-sm text-red-600">{t.dealerMustAgree}</p>
                </div>
              )}

              <button
                onClick={handleProceedToForm}
                className={`w-full px-4 py-4 rounded-lg font-semibold transition ${
                  privacyAgreed && obligationAgreed
                    ? 'bg-primary-600 text-white hover:bg-primary-700'
                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                }`}
              >
                {t.dealerProceedToApply}
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Step 2: Application Form
  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.dealerApplication}</h1>
            <p className="text-gray-600">{t.dealerApplicationSubtitle}</p>
          </div>

          {/* Step indicator */}
          <div className="flex items-center justify-center gap-3 mb-8">
            <div className="flex items-center gap-2 text-green-600">
              <div className="w-8 h-8 rounded-full bg-green-600 text-white flex items-center justify-center text-sm font-bold">✓</div>
              <span className="text-sm font-medium">{t.dealerAgreementTitle}</span>
            </div>
            <div className="w-8 h-px bg-gray-300"></div>
            <div className="flex items-center gap-2 text-primary-600">
              <div className="w-8 h-8 rounded-full bg-primary-600 text-white flex items-center justify-center text-sm font-bold">2</div>
              <span className="text-sm font-medium">{t.dealerApplication}</span>
            </div>
          </div>

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

          {/* Application Form */}
          <form onSubmit={handleSubmit} className="bg-white rounded-xl shadow-lg p-6">
            <div className="space-y-4">
              {/* Business Name */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.businessName} *
                </label>
                <input
                  type="text"
                  required
                  value={formData.business_name}
                  onChange={(e) => setFormData({ ...formData, business_name: e.target.value })}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  placeholder={language === 'ko' ? '예: 홍길동 자동차' : 'e.g., ABC Motors'}
                />
              </div>

              {/* Business Number (Optional) */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.businessNumber} ({language === 'ko' ? '선택' : 'Optional'})
                </label>
                <input
                  type="text"
                  value={formData.business_number}
                  onChange={(e) => setFormData({ ...formData, business_number: e.target.value })}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  placeholder={language === 'ko' ? '000-00-00000' : '000-00-00000'}
                />
              </div>

              {/* Real Name */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.realName} *
                </label>
                <input
                  type="text"
                  required
                  value={formData.real_name}
                  onChange={(e) => setFormData({ ...formData, real_name: e.target.value })}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                />
              </div>

              {/* Phone */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.phone} *
                </label>
                <input
                  type="tel"
                  required
                  value={formData.phone}
                  onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  placeholder="010-1234-5678"
                />
              </div>

              <hr className="my-6" />

              <h3 className="font-semibold text-gray-800">
                {language === 'ko' ? '출금 계좌 정보' : 'Withdrawal Bank Account'}
              </h3>

              {/* Bank Name */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.bankName} *
                </label>
                <select
                  required
                  value={formData.bank_name}
                  onChange={(e) => setFormData({ ...formData, bank_name: e.target.value })}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                >
                  <option value="">{language === 'ko' ? '은행 선택' : 'Select Bank'}</option>
                  <option value="KB국민은행">KB국민은행</option>
                  <option value="신한은행">신한은행</option>
                  <option value="하나은행">하나은행</option>
                  <option value="우리은행">우리은행</option>
                  <option value="NH농협은행">NH농협은행</option>
                  <option value="카카오뱅크">카카오뱅크</option>
                  <option value="토스뱅크">토스뱅크</option>
                  <option value="IBK기업은행">IBK기업은행</option>
                  <option value="케이뱅크">케이뱅크</option>
                  <option value="Other">Other</option>
                </select>
              </div>

              {/* Bank Account */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.bankAccount} *
                </label>
                <input
                  type="text"
                  required
                  value={formData.bank_account}
                  onChange={(e) => setFormData({ ...formData, bank_account: e.target.value })}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  placeholder="1234567890123"
                />
              </div>

              {/* Account Holder */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.accountHolder} *
                </label>
                <input
                  type="text"
                  required
                  value={formData.account_holder}
                  onChange={(e) => setFormData({ ...formData, account_holder: e.target.value })}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                />
              </div>
            </div>

            {/* Submit Button */}
            <button
              type="submit"
              disabled={loading}
              className="w-full mt-6 px-4 py-4 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed transition font-semibold"
            >
              {loading ? (
                <span className="flex items-center justify-center gap-2">
                  <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                  {t.loading}
                </span>
              ) : (
                t.submitApplication
              )}
            </button>

            <p className="text-xs text-gray-500 text-center mt-4">
              {language === 'ko'
                ? '* 신청 후 관리자 승인이 필요합니다. 승인까지 1-2일 소요될 수 있습니다.'
                : '* Admin approval required. May take 1-2 days to process.'}
            </p>
          </form>
        </div>
      </div>
    </div>
  );
}
