'use client';

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

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

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

  const [isEditing, setIsEditing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [copied, setCopied] = useState(false);

  // 탈퇴 관련 state
  const [showWithdrawModal, setShowWithdrawModal] = useState(false);
  const [withdrawPassword, setWithdrawPassword] = useState('');
  const [withdrawReason, setWithdrawReason] = useState('');
  const [withdrawLoading, setWithdrawLoading] = useState(false);

  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    country: '',
  });

  useEffect(() => {
    if (!user) {
      router.push('/login');
      return;
    }
    setFormData({
      name: user.name || '',
      phone: user.phone || '',
      country: user.country || 'Mongolia',
    });
  }, [user, router]);

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

    setLoading(true);
    setMessage(null);

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

      if (response.ok) {
        const updatedUser = await response.json();
        setUser(updatedUser);
        setMessage({ type: 'success', text: t.profileUpdated });
        setIsEditing(false);
      } else {
        const error = await response.json();
        setMessage({ type: 'error', text: error.detail || t.updateFailed });
      }
    } catch (error) {
      console.error('Update failed:', error);
      setMessage({ type: 'error', text: t.updateFailed });
    } finally {
      setLoading(false);
    }
  };

  const copyReferralLink = () => {
    if (!user?.referral_code) return;

    const referralLink = `${window.location.origin}/register?ref=${user.referral_code}`;
    navigator.clipboard.writeText(referralLink).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  const handleWithdraw = async () => {
    if (!withdrawPassword) {
      setMessage({ type: 'error', text: language === 'ko' ? '비밀번호를 입력해주세요.' : 'Please enter your password.' });
      return;
    }

    setWithdrawLoading(true);
    try {
      await authApi.requestWithdrawal(withdrawPassword, withdrawReason || undefined);
      setShowWithdrawModal(false);
      // 로그아웃 처리
      localStorage.removeItem('token');
      setUser(null);
      router.push('/');
      alert(language === 'ko' ? '탈퇴 요청이 완료되었습니다.' : 'Withdrawal request completed.');
    } catch (error: any) {
      const detail = error.response?.data?.detail || (language === 'ko' ? '탈퇴 요청 실패' : 'Withdrawal request failed');
      setMessage({ type: 'error', text: detail });
    } finally {
      setWithdrawLoading(false);
    }
  };

  if (!user) {
    return null;
  }

  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.profileTitle}</h1>
            <p className="text-gray-600">{t.profileSubtitle}</p>
          </div>

          {/* Profile Card */}
          <div className="bg-white rounded-xl shadow-lg p-6 mb-6">
            {/* CC Balance Display */}
            <div className="bg-gradient-to-r from-primary-600 to-primary-700 text-white rounded-lg p-4 mb-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-primary-100 text-sm">{t.ccBalance}</p>
                  <p className="text-3xl font-bold">{user.cc_balance} CC</p>
                </div>
                <div className="text-5xl opacity-50">💰</div>
              </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>
            )}

            {/* Profile Form */}
            <div className="space-y-4">
              {/* Email (non-editable) */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t.email}</label>
                <div className="w-full px-4 py-3 bg-gray-100 border border-gray-200 rounded-lg text-gray-600">
                  {user.email}
                </div>
              </div>

              {/* Name */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t.name}</label>
                {isEditing ? (
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, 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={t.name}
                  />
                ) : (
                  <div className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-lg">
                    {user.name || '-'}
                  </div>
                )}
              </div>

              {/* Phone */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t.phone}</label>
                {isEditing ? (
                  <input
                    type="tel"
                    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={t.phone}
                  />
                ) : (
                  <div className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-lg">
                    {user.phone || '-'}
                  </div>
                )}
              </div>

              {/* Country */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t.country}</label>
                {isEditing ? (
                  <select
                    value={formData.country}
                    onChange={(e) => setFormData({ ...formData, country: 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="Mongolia">Mongolia</option>
                    <option value="Korea">Korea</option>
                    <option value="Russia">Russia</option>
                    <option value="China">China</option>
                    <option value="Other">Other</option>
                  </select>
                ) : (
                  <div className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-lg">
                    {user.country || 'Mongolia'}
                  </div>
                )}
              </div>
            </div>

            {/* Edit/Save Buttons */}
            <div className="mt-6 flex gap-3">
              {isEditing ? (
                <>
                  <button
                    onClick={() => {
                      setIsEditing(false);
                      setFormData({
                        name: user.name || '',
                        phone: user.phone || '',
                        country: user.country || 'Mongolia',
                      });
                    }}
                    className="flex-1 px-4 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition"
                  >
                    {t.close}
                  </button>
                  <button
                    onClick={handleSave}
                    disabled={loading}
                    className="flex-1 px-4 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 transition"
                  >
                    {loading ? t.saving : t.saveChanges}
                  </button>
                </>
              ) : (
                <button
                  onClick={() => setIsEditing(true)}
                  className="w-full px-4 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition"
                >
                  {t.editProfile}
                </button>
              )}
            </div>
          </div>

          {/* Referral Code Card */}
          <div className="bg-white rounded-xl shadow-lg p-6">
            <h2 className="text-xl font-semibold text-gray-800 mb-4">{t.myReferralCode}</h2>

            <div className="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-lg p-4 mb-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-green-600 mb-1">
                    {language === 'ko' ? '친구를 초대하고 보상을 받으세요!' : 'Invite friends and get rewards!'}
                  </p>
                  <p className="text-2xl font-mono font-bold text-green-700">
                    {user.referral_code || '-'}
                  </p>
                </div>
                <div className="text-4xl">🎁</div>
              </div>
            </div>

            <button
              onClick={copyReferralLink}
              className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition"
            >
              {copied ? (
                <>
                  <span>✓</span>
                  <span>{t.copied}</span>
                </>
              ) : (
                <>
                  <span>📋</span>
                  <span>{t.copyReferralCode}</span>
                </>
              )}
            </button>

            {copied && (
              <p className="mt-2 text-sm text-green-600 text-center">{t.referralLinkCopied}</p>
            )}
          </div>

          {/* Account Info */}
          <div className="mt-6 text-center text-sm text-gray-500">
            <p>
              {language === 'ko' ? '가입일: ' : 'Member since: '}
              {new Date(user.created_at).toLocaleDateString()}
            </p>
          </div>

          {/* Danger Zone - Account Withdrawal */}
          <div className="mt-8 bg-white rounded-xl shadow-lg p-6 border border-red-100">
            <h2 className="text-xl font-semibold text-red-600 mb-4">
              {language === 'ko' ? '계정 탈퇴' : 'Account Withdrawal'}
            </h2>
            <p className="text-gray-600 text-sm mb-4">
              {language === 'ko'
                ? '계정을 탈퇴하면 모든 데이터가 삭제됩니다. 이 작업은 되돌릴 수 없습니다.'
                : 'Once you withdraw your account, all your data will be deleted. This action cannot be undone.'}
            </p>
            <button
              onClick={() => setShowWithdrawModal(true)}
              className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition"
            >
              {language === 'ko' ? '계정 탈퇴 요청' : 'Request Account Withdrawal'}
            </button>
          </div>
        </div>
      </div>

      {/* Withdrawal Modal */}
      {showWithdrawModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full p-6">
            <h3 className="text-xl font-bold text-red-600 mb-4">
              {language === 'ko' ? '계정 탈퇴' : 'Account Withdrawal'}
            </h3>

            <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-4">
              <p className="text-red-700 text-sm">
                {language === 'ko'
                  ? '⚠️ 주의: 탈퇴 후 모든 데이터(CC 잔액, 구매 기록 등)가 삭제됩니다.'
                  : '⚠️ Warning: After withdrawal, all data (CC balance, purchase history, etc.) will be deleted.'}
              </p>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {language === 'ko' ? '비밀번호 확인' : 'Confirm Password'} *
                </label>
                <input
                  type="password"
                  value={withdrawPassword}
                  onChange={(e) => setWithdrawPassword(e.target.value)}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500"
                  placeholder={language === 'ko' ? '비밀번호를 입력하세요' : 'Enter your password'}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {language === 'ko' ? '탈퇴 사유 (선택)' : 'Reason for withdrawal (optional)'}
                </label>
                <textarea
                  value={withdrawReason}
                  onChange={(e) => setWithdrawReason(e.target.value)}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 resize-none"
                  rows={3}
                  placeholder={language === 'ko' ? '탈퇴 사유를 입력해주세요' : 'Please enter your reason'}
                />
              </div>
            </div>

            <div className="flex gap-3 mt-6">
              <button
                onClick={() => {
                  setShowWithdrawModal(false);
                  setWithdrawPassword('');
                  setWithdrawReason('');
                }}
                className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition"
              >
                {language === 'ko' ? '취소' : 'Cancel'}
              </button>
              <button
                onClick={handleWithdraw}
                disabled={withdrawLoading}
                className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 transition"
              >
                {withdrawLoading
                  ? (language === 'ko' ? '처리 중...' : 'Processing...')
                  : (language === 'ko' ? '탈퇴하기' : 'Withdraw')}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
