'use client';

import { useState, useEffect } from 'react';
import { verificationApi } from '@/lib/api';
import { useTranslation } from '@/lib/i18n';

interface PhoneVerificationModalProps {
  isOpen: boolean;
  onClose: () => void;
  onVerified: () => void;
  currentPhone?: string;
}

export default function PhoneVerificationModal({
  isOpen,
  onClose,
  onVerified,
  currentPhone
}: PhoneVerificationModalProps) {
  const { language, t } = useTranslation();

  const [step, setStep] = useState<'phone' | 'verify'>('phone');
  const [phone, setPhone] = useState(currentPhone || '');
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [countdown, setCountdown] = useState(0);

  // Reset state when modal opens
  useEffect(() => {
    if (isOpen) {
      setStep('phone');
      setPhone(currentPhone || '');
      setCode('');
      setError('');
      setSuccess('');
      setCountdown(0);
    }
  }, [isOpen, currentPhone]);

  // Countdown timer
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);

  const handleSendCode = async () => {
    if (!phone) {
      setError(t.enterPhoneNumber || 'Please enter your phone number');
      return;
    }

    setLoading(true);
    setError('');

    try {
      await verificationApi.sendPhoneCode(phone, language);
      setSuccess(t.verificationCodeSent || 'Verification code sent');
      setStep('verify');
      setCountdown(60);
    } catch (err: any) {
      setError(err.response?.data?.detail || t.failedToSendCode || 'Failed to send code');
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyCode = async () => {
    if (!code) {
      setError(t.enterVerificationCode || 'Please enter the verification code');
      return;
    }

    setLoading(true);
    setError('');

    try {
      await verificationApi.verifyPhoneCode(phone, code);
      setSuccess(t.phoneVerifiedSuccess || 'Phone verified successfully');
      setTimeout(() => {
        onVerified();
        onClose();
      }, 1000);
    } catch (err: any) {
      setError(err.response?.data?.detail || t.invalidVerificationCode || 'Invalid code');
    } finally {
      setLoading(false);
    }
  };

  const handleResendCode = async () => {
    if (countdown > 0) return;
    await handleSendCode();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg max-w-md w-full p-6 shadow-xl">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-bold text-gray-800">
            {t.phoneVerification || 'Phone Verification'}
          </h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {error && (
          <div className="bg-red-50 text-red-600 p-3 rounded-md mb-4 text-sm">
            {error}
          </div>
        )}

        {success && (
          <div className="bg-green-50 text-green-600 p-3 rounded-md mb-4 text-sm">
            {success}
          </div>
        )}

        {step === 'phone' && (
          <div>
            <p className="text-gray-600 mb-4 text-sm">
              {t.phoneVerificationDesc || 'Please verify your phone number to continue with CC charging.'}
            </p>

            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {t.phone || 'Phone Number'}
              </label>
              <input
                type="tel"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                className="w-full border border-gray-300 rounded-md px-4 py-2 focus:ring-primary-500 focus:border-primary-500"
                placeholder="+976 XXXX XXXX"
              />
              <p className="text-xs text-gray-500 mt-1">
                Include country code (e.g., +976 for Mongolia, +7 for Russia)
              </p>
            </div>

            <button
              onClick={handleSendCode}
              disabled={loading}
              className="w-full bg-primary-600 text-white py-3 rounded-md hover:bg-primary-700 transition disabled:opacity-50"
            >
              {loading ? (t.sending || 'Sending...') : (t.sendVerificationCode || 'Send Verification Code')}
            </button>
          </div>
        )}

        {step === 'verify' && (
          <div>
            <p className="text-gray-600 mb-4 text-sm">
              {t.verificationCodeSentTo || 'We sent a verification code to'} <strong>{phone}</strong>
            </p>

            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {t.verificationCode || 'Verification Code'}
              </label>
              <input
                type="text"
                value={code}
                onChange={(e) => setCode(e.target.value)}
                className="w-full border border-gray-300 rounded-md px-4 py-2 focus:ring-primary-500 focus:border-primary-500 text-center text-2xl tracking-widest"
                placeholder="000000"
                maxLength={6}
              />
            </div>

            <button
              onClick={handleVerifyCode}
              disabled={loading}
              className="w-full bg-primary-600 text-white py-3 rounded-md hover:bg-primary-700 transition disabled:opacity-50 mb-4"
            >
              {loading ? (t.verifying || 'Verifying...') : (t.verifyPhone || 'Verify Phone')}
            </button>

            <div className="flex justify-between items-center">
              <button
                onClick={() => setStep('phone')}
                className="text-gray-600 hover:underline text-sm"
              >
                ← {t.changeEmail?.replace('Email', 'Phone') || 'Change Phone'}
              </button>
              <button
                onClick={handleResendCode}
                disabled={countdown > 0 || loading}
                className="text-primary-600 hover:underline text-sm disabled:text-gray-400"
              >
                {countdown > 0 ? `${t.resendIn || 'Resend in'} ${countdown}s` : (t.resendCode || 'Resend Code')}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
