import React, { useState, useEffect } from 'react';
import { User, Mail, Lock, ArrowRight, ChevronLeft, Phone, MapPin, ShieldCheck } from 'lucide-react';
import { Capacitor } from '@capacitor/core';
import { GoogleAuth } from '@codetrix-studio/capacitor-google-auth';

interface SignupPageProps {
  onBack: () => void;
  onSuccess: () => void;
}

const SignupPage: React.FC<SignupPageProps> = ({ onBack, onSuccess }) => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    password: '',
    confirmPassword: '',
    phone: '',
    address: ''
  });
  const [step, setStep] = useState<'form' | 'otp'>('form');
  const [otp, setOtp] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const handleGoogleLogin = async (googleResponse: any) => {
    setError('');
    setIsLoading(true);
    try {
      const response = await fetch(`/api/v1/auth/google`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ credential: googleResponse.credential }),
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.message || 'Đăng ký bằng Google thất bại');
      }

      localStorage.removeItem('guest_token');
      localStorage.removeItem('guest_user');
      localStorage.setItem('token', data.access_token);
      localStorage.setItem('user', JSON.stringify(data.user));

      // Tự động gia nhập tour nếu có pendingInviteToken
      const pendingInviteToken = localStorage.getItem('pendingInviteToken');
      if (pendingInviteToken) {
        console.log('[SignupPage] Auto-joining tour with pending token after Google signup');
        await fetch(`/api/v1/tours/join-by-token`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${data.access_token}`,
          },
          body: JSON.stringify({ token: pendingInviteToken }),
        }).then(res => {
          if (res.ok) {
            localStorage.removeItem('pendingInviteToken');
            console.log('[SignupPage] Successfully joined tour after Google signup');
          } else {
            console.warn('[SignupPage] Failed to join tour after Google signup:', res.status);
          }
        }).catch((e) => console.error('Lỗi tự động gia nhập:', e));
      }

      onSuccess();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const handleNativeGoogleLogin = async () => {
    setError('');
    setIsLoading(true);
    try {
      const user = await GoogleAuth.signIn();
      console.log('[SignupPage] Native Google user received:', user);
      
      const idToken = user.authentication.idToken;
      if (!idToken) {
        throw new Error('Không nhận được token từ Google.');
      }
      
      const response = await fetch(`/api/v1/auth/google`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ credential: idToken }),
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.message || 'Đăng ký bằng Google thất bại');
      }

      localStorage.removeItem('guest_token');
      localStorage.removeItem('guest_user');
      localStorage.setItem('token', data.access_token);
      localStorage.setItem('user', JSON.stringify(data.user));

      const pendingInviteToken = localStorage.getItem('pendingInviteToken');
      if (pendingInviteToken) {
        console.log('[SignupPage] Auto-joining tour with pending token after Google signup');
        await fetch(`/api/v1/tours/join-by-token`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${data.access_token}`,
          },
          body: JSON.stringify({ token: pendingInviteToken }),
        }).then(res => {
          if (res.ok) {
            localStorage.removeItem('pendingInviteToken');
            console.log('[SignupPage] Successfully joined tour after Google signup');
          } else {
            console.warn('[SignupPage] Failed to join tour after Google signup:', res.status);
          }
        }).catch((e) => console.error('Lỗi tự động gia nhập:', e));
      }

      onSuccess();
    } catch (err: any) {
      console.error('[SignupPage] Native Google signup error:', err);
      if (err?.message !== 'Sign in window was closed' && err?.message !== '12501') {
        setError(err.message || 'Đăng ký bằng Google thất bại');
      }
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (step !== 'form' || Capacitor.isNativePlatform()) return;

    const timer = setTimeout(() => {
      if (typeof window !== 'undefined' && (window as any).google) {
        try {
          (window as any).google.accounts.id.initialize({
            client_id: (import.meta as any).env.VITE_GOOGLE_CLIENT_ID || '864264639911-dummyid.apps.googleusercontent.com',
            callback: handleGoogleLogin,
          });
          
          (window as any).google.accounts.id.renderButton(
            document.getElementById('google-signin-btn-signup'),
            { theme: 'outline', size: 'large', width: '380' }
          );
        } catch (e) {
          console.error('Lỗi khởi tạo Google Sign-in:', e);
        }
      }
    }, 100);

    return () => clearTimeout(timer);
  }, [step]);

  const handleChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

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

    setIsLoading(true);
    try {
      if (step === 'form') {
        if (formData.password !== formData.confirmPassword) {
          setError('Mật khẩu xác nhận không khớp');
          setIsLoading(false);
          return;
        }

        const response = await fetch(`/api/v1/auth/signup/request`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            email: formData.email,
            password: formData.password,
            name: formData.name,
            phone: formData.phone || undefined,
            address: formData.address || undefined
          }),
        });
        const data = await response.json();
        if (!response.ok) throw new Error(data.message || 'Yêu cầu đăng ký thất bại');
        
        setStep('otp');
      } else {
        // Xác thực mã OTP bước hoàn tất
        const guestUserStr = localStorage.getItem('guest_user');
        const guestUser = guestUserStr ? JSON.parse(guestUserStr) : null;
        const guestId = guestUser ? guestUser.id : undefined;

        const response = await fetch(`/api/v1/auth/signup/verify`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            email: formData.email,
            otp: otp,
            guestId: guestId
          }),
        });
        const data = await response.json();
        if (!response.ok) throw new Error(data.message || 'Mã OTP không chính xác');

        // Dọn dẹp session lữ khách sau khi đăng ký thành công
        localStorage.removeItem('guest_token');
        localStorage.removeItem('guest_user');
        
        onSuccess();
      }
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-[var(--background)] py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8 bg-[var(--surface)] p-10 rounded-3xl shadow-2xl">
        <button
          onClick={onBack}
          className="absolute top-6 left-6 text-[var(--text-muted)] hover:text-[var(--text-secondary)] transition-colors"
        >
          <ChevronLeft className="w-6 h-6" />
        </button>

        <div className="mb-10">
          <h1 className="text-3xl font-extrabold text-[var(--text-primary)]">
            {step === 'form' ? 'Tạo tài khoản mới' : 'Xác thực tài khoản'}
          </h1>
          <p className="text-[var(--text-muted)] mt-2 font-medium">
            {step === 'form' 
              ? 'Khám phá các tính năng lập kế hoạch chuyên nghiệp.' 
              : `Vui lòng nhập mã OTP đã được gửi tới ${formData.email}`}
          </p>
        </div>

        {error && (
          <div className="mb-6 p-4 bg-red-50 text-red-600 rounded-2xl text-sm font-bold animate-in fade-in slide-in-from-top-1">
            {error}
          </div>
        )}

        <form className="space-y-5" onSubmit={handleSubmit}>
          {step === 'form' ? (
            <>
              <div className="space-y-1.5">
                <label className="text-sm font-bold text-[var(--text-primary)] ml-1">Họ và tên</label>
                <div className="relative group">
                  <User className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-[var(--text-muted)] group-focus-within:text-blue-500 transition-colors" />
                  <input
                    required
                    type="text"
                    placeholder="Nhập họ và tên của bạn"
                    value={formData.name}
                    onChange={(e) => handleChange('name', e.target.value)}
                    className="w-full pl-12 pr-4 py-4 bg-[var(--background)] border border-[var(--border)] rounded-2xl focus:ring-2 focus:ring-blue-500 focus:bg-[var(--surface)] outline-none transition-all"
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-sm font-bold text-[var(--text-primary)] ml-1">Email</label>
                <div className="relative group">
                  <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-[var(--text-muted)] group-focus-within:text-blue-500 transition-colors" />
                  <input
                    required
                    type="email"
                    placeholder="Nhập email của bạn"
                    value={formData.email}
                    onChange={(e) => handleChange('email', e.target.value)}
                    className="w-full pl-12 pr-4 py-4 bg-[var(--background)] border border-[var(--border)] rounded-2xl focus:ring-2 focus:ring-blue-500 focus:bg-[var(--surface)] outline-none transition-all"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-sm font-bold text-[var(--text-primary)] ml-1">Mật khẩu</label>
                  <div className="relative group">
                    <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-[var(--text-muted)] group-focus-within:text-blue-500 transition-colors" />
                    <input
                      required
                      type="password"
                      placeholder="Nhập mật khẩu"
                      value={formData.password}
                      onChange={(e) => handleChange('password', e.target.value)}
                      className="w-full pl-12 pr-4 py-4 bg-[var(--background)] border border-[var(--border)] rounded-2xl focus:ring-2 focus:ring-blue-500 focus:bg-[var(--surface)] outline-none transition-all"
                    />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <label className="text-sm font-bold text-[var(--text-primary)] ml-1">Xác nhận mật khẩu</label>
                  <div className="relative group">
                    <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-[var(--text-muted)] group-focus-within:text-blue-500 transition-colors" />
                    <input
                      required
                      type="password"
                      placeholder="Xác nhận mật khẩu"
                      value={formData.confirmPassword}
                      onChange={(e) => handleChange('confirmPassword', e.target.value)}
                      className="w-full pl-12 pr-4 py-4 bg-[var(--background)] border border-[var(--border)] rounded-2xl focus:ring-2 focus:ring-blue-500 focus:bg-[var(--surface)] outline-none transition-all"
                    />
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-sm font-bold text-[var(--text-primary)] ml-1">Số điện thoại</label>
                  <div className="relative group">
                    <Phone className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-[var(--text-muted)] group-focus-within:text-blue-500 transition-colors" />
                    <input
                      type="tel"
                      placeholder="Nhập số điện thoại"
                      value={formData.phone}
                      onChange={(e) => handleChange('phone', e.target.value)}
                      className="w-full pl-12 pr-4 py-4 bg-[var(--background)] border border-[var(--border)] rounded-2xl focus:ring-2 focus:ring-blue-500 focus:bg-[var(--surface)] outline-none transition-all"
                    />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <label className="text-sm font-bold text-[var(--text-primary)] ml-1">Địa chỉ</label>
                  <div className="relative group">
                    <MapPin className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-[var(--text-muted)] group-focus-within:text-blue-500 transition-colors" />
                    <input
                      type="text"
                      placeholder="Nhập địa chỉ"
                      value={formData.address}
                      onChange={(e) => handleChange('address', e.target.value)}
                      className="w-full pl-12 pr-4 py-4 bg-[var(--background)] border border-[var(--border)] rounded-2xl focus:ring-2 focus:ring-blue-500 focus:bg-[var(--surface)] outline-none transition-all"
                    />
                  </div>
                </div>
              </div>
            </>
          ) : (
            <div className="space-y-2">
              <label className="text-sm font-bold text-[var(--text-primary)] ml-1">Mã xác thực OTP</label>
              <div className="relative group">
                <ShieldCheck className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-[var(--text-muted)] group-focus-within:text-blue-500 transition-colors" />
                <input
                  required
                  type="text"
                  maxLength={6}
                  placeholder="Nhập 6 số mã OTP"
                  value={otp}
                  onChange={(e) => setOtp(e.target.value.replace(/\D/g, ''))}
                  className="w-full pl-12 pr-4 py-4 bg-[var(--background)] border border-[var(--border)] rounded-2xl text-center font-bold tracking-[0.5em] text-lg focus:ring-2 focus:ring-blue-500 focus:bg-[var(--surface)] outline-none transition-all"
                />
              </div>
            </div>
          )}

          <button
            disabled={isLoading}
            type="submit"
            className="w-full flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 text-white font-bold py-5 rounded-2xl shadow-xl shadow-blue-100 transition-all active:scale-[0.98] disabled:opacity-50 mt-4"
          >
            {isLoading ? 'Đang xử lý...' : step === 'form' ? 'Tạo tài khoản' : 'Xác nhận kích hoạt'}
            {!isLoading && <ArrowRight className="w-5 h-5" />}
          </button>
        </form>

        {step === 'form' && (
          <>
            <div className="relative my-6 flex items-center justify-center">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-[var(--border)]"></div>
              </div>
              <span className="relative px-3 bg-[var(--surface)] text-xs font-bold text-[var(--text-muted)] uppercase">Hoặc</span>
            </div>

            {Capacitor.isNativePlatform() ? (
              <button
                type="button"
                onClick={handleNativeGoogleLogin}
                className="w-full flex items-center justify-center gap-3 bg-white hover:bg-slate-50 text-slate-800 font-bold py-3.5 px-4 rounded-2xl border border-slate-200 transition-all active:scale-[0.98] cursor-pointer text-sm shadow-sm"
              >
                <svg className="w-5 h-5" viewBox="0 0 24 24">
                  <path
                    fill="#EA4335"
                    d="M12.24 10.285V14.4h6.887c-.648 2.41-2.519 4.114-5.136 4.114-3.51 0-6.357-2.89-6.357-6.457 0-3.568 2.848-6.458 6.357-6.458 1.614 0 3.08.618 4.19 1.625l3.03-3.03C19.045 2.11 15.895 1 12.24 1 6.033 1 1 6.033 1 12.24s5.033 11.24 11.24 11.24c5.84 0 10.74-4.14 11.24-9.84v-3.355H12.24z"
                  />
                </svg>
                Đăng ký bằng Google
              </button>
            ) : (
              <div id="google-signin-btn-signup" className="w-full flex justify-center"></div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default SignupPage;
