'use client';

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

type RegistrationStep = 'email' | 'verify' | 'details';

export default function RegisterPage() {
  const router = useRouter();
  const { language, t } = useTranslation();

  const [step, setStep] = useState<RegistrationStep>('email');
  const [formData, setFormData] = useState({
    email: '',
    verificationCode: '',
    password: '',
    confirmPassword: '',
    name: '',
    phone: '',
    country: 'Mongolia',
  });
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);

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

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
    setError('');
  };

  const handleSendCode = async () => {
    if (!formData.email) {
      setError(t.enterEmail || 'Please enter your email');
      return;
    }

    setLoading(true);
    setError('');

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

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

    setLoading(true);
    setError('');

    try {
      await verificationApi.verifyEmailCodePreregister(formData.email, formData.verificationCode);
      setSuccess(t.emailVerified || 'Email verified successfully');
      setStep('details');
    } catch (err: any) {
      setError(err.response?.data?.detail || t.invalidVerificationCode || 'Invalid verification code');
    } finally {
      setLoading(false);
    }
  };

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

    setLoading(true);
    setError('');

    try {
      await verificationApi.sendEmailCodePreregister(formData.email, language);
      setSuccess(t.verificationCodeResent || 'New verification code sent');
      setCountdown(60);
    } catch (err: any) {
      setError(err.response?.data?.detail || t.failedToSendCode || 'Failed to send verification code');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (formData.password !== formData.confirmPassword) {
      setError(t.passwordsDoNotMatch || 'Passwords do not match');
      return;
    }

    if (formData.password.length < 6) {
      setError(t.passwordTooShort || 'Password must be at least 6 characters');
      return;
    }

    setLoading(true);

    try {
      await authApi.register({
        email: formData.email,
        password: formData.password,
        name: formData.name,
        phone: formData.phone,
        country: formData.country,
      });

      router.push('/login?registered=true');
    } catch (err: any) {
      setError(err.response?.data?.detail || t.registrationFailed || 'Registration failed. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center py-12 px-4">
      <div className="max-w-md w-full">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-800">{t.createAccount || 'Create Account'}</h1>
          <p className="text-gray-600 mt-2">{t.joinAutonet || 'Join AutonetSellCar today'}</p>
        </div>

        {/* Progress Steps */}
        <div className="flex items-center justify-center mb-8">
          <div className={`flex items-center ${step === 'email' ? 'text-primary-600' : 'text-gray-400'}`}>
            <div className={`w-8 h-8 rounded-full flex items-center justify-center ${step === 'email' ? 'bg-primary-600 text-white' : step === 'verify' || step === 'details' ? 'bg-green-500 text-white' : 'bg-gray-300'}`}>
              {step === 'verify' || step === 'details' ? '✓' : '1'}
            </div>
            <span className="ml-2 text-sm font-medium">{t.email || 'Email'}</span>
          </div>
          <div className="w-12 h-0.5 bg-gray-300 mx-2"></div>
          <div className={`flex items-center ${step === 'verify' ? 'text-primary-600' : 'text-gray-400'}`}>
            <div className={`w-8 h-8 rounded-full flex items-center justify-center ${step === 'verify' ? 'bg-primary-600 text-white' : step === 'details' ? 'bg-green-500 text-white' : 'bg-gray-300'}`}>
              {step === 'details' ? '✓' : '2'}
            </div>
            <span className="ml-2 text-sm font-medium">{t.verify || 'Verify'}</span>
          </div>
          <div className="w-12 h-0.5 bg-gray-300 mx-2"></div>
          <div className={`flex items-center ${step === 'details' ? 'text-primary-600' : 'text-gray-400'}`}>
            <div className={`w-8 h-8 rounded-full flex items-center justify-center ${step === 'details' ? 'bg-primary-600 text-white' : 'bg-gray-300'}`}>
              3
            </div>
            <span className="ml-2 text-sm font-medium">{t.details || 'Details'}</span>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-md p-8">
          {error && (
            <div className="bg-red-50 text-red-600 p-4 rounded-md mb-6">
              {error}
            </div>
          )}

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

          {/* Step 1: Email */}
          {step === 'email' && (
            <div>
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.email || 'Email'} *
                </label>
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange}
                  className="w-full border border-gray-300 rounded-md px-4 py-2 focus:ring-primary-500 focus:border-primary-500"
                  placeholder="your@email.com"
                  required
                />
              </div>

              <button
                type="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 2: Verify Email */}
          {step === 'verify' && (
            <div>
              <p className="text-sm text-gray-600 mb-4">
                {t.verificationCodeSentTo || 'We sent a verification code to'} <strong>{formData.email}</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"
                  name="verificationCode"
                  value={formData.verificationCode}
                  onChange={handleChange}
                  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}
                  required
                />
              </div>

              <button
                type="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.verifyCode || 'Verify Code')}
              </button>

              <div className="flex justify-between items-center">
                <button
                  type="button"
                  onClick={() => setStep('email')}
                  className="text-gray-600 hover:underline text-sm"
                >
                  ← {t.changeEmail || 'Change Email'}
                </button>
                <button
                  type="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>
          )}

          {/* Step 3: Account Details */}
          {step === 'details' && (
            <form onSubmit={handleSubmit}>
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.email || 'Email'}
                </label>
                <div className="flex items-center">
                  <input
                    type="email"
                    value={formData.email}
                    disabled
                    className="w-full border border-gray-300 rounded-md px-4 py-2 bg-gray-50 text-gray-500"
                  />
                  <span className="ml-2 text-green-500">✓</span>
                </div>
              </div>

              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.name || 'Name'}
                </label>
                <input
                  type="text"
                  name="name"
                  value={formData.name}
                  onChange={handleChange}
                  className="w-full border border-gray-300 rounded-md px-4 py-2 focus:ring-primary-500 focus:border-primary-500"
                  placeholder={t.yourName || 'Your name'}
                />
              </div>

              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.phone || 'Phone'}
                </label>
                <input
                  type="tel"
                  name="phone"
                  value={formData.phone}
                  onChange={handleChange}
                  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"
                />
              </div>

              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.country || 'Country'}
                </label>
                <select
                  name="country"
                  value={formData.country}
                  onChange={handleChange}
                  className="w-full border border-gray-300 rounded-md px-4 py-2 focus:ring-primary-500 focus:border-primary-500"
                >
                  <option value="Mongolia">Mongolia</option>
                  <option value="Russia">Russia</option>
                  <option value="Kazakhstan">Kazakhstan</option>
                  <option value="Other">Other</option>
                </select>
              </div>

              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.password || 'Password'} *
                </label>
                <div className="relative">
                  <input
                    type={showPassword ? 'text' : 'password'}
                    name="password"
                    value={formData.password}
                    onChange={handleChange}
                    className="w-full border border-gray-300 rounded-md px-4 py-2 pr-10 focus:ring-primary-500 focus:border-primary-500"
                    placeholder="••••••••"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                  >
                    {showPassword ? (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                      </svg>
                    )}
                  </button>
                </div>
              </div>

              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t.confirmPassword || 'Confirm Password'} *
                </label>
                <div className="relative">
                  <input
                    type={showConfirmPassword ? 'text' : 'password'}
                    name="confirmPassword"
                    value={formData.confirmPassword}
                    onChange={handleChange}
                    className="w-full border border-gray-300 rounded-md px-4 py-2 pr-10 focus:ring-primary-500 focus:border-primary-500"
                    placeholder="••••••••"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                  >
                    {showConfirmPassword ? (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                      </svg>
                    )}
                  </button>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full bg-primary-600 text-white py-3 rounded-md hover:bg-primary-700 transition disabled:opacity-50"
              >
                {loading ? (t.creatingAccount || 'Creating account...') : (t.createAccount || 'Create Account')}
              </button>
            </form>
          )}

          <p className="mt-6 text-center text-gray-600">
            {t.alreadyHaveAccount || 'Already have an account?'}{' '}
            <Link href="/login" className="text-primary-600 hover:underline">
              {t.signIn || 'Sign in'}
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}
