import React, { useState, useEffect } from 'react';
import { X, Mail, Lock, ArrowRight, Loader2 } from 'lucide-react';
import { Capacitor } from '@capacitor/core';
import { GoogleAuth } from '@codetrix-studio/capacitor-google-auth';

interface LoginModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSwitchToSignup?: () => void;
  onLoginSuccess?: (user: any) => void;
}

export const LoginModal: React.FC<LoginModalProps> = ({ isOpen, onClose, onSwitchToSignup, onLoginSuccess }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = 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 nhập Google thất bại');
      }

      localStorage.setItem('token', data.access_token);
      localStorage.setItem('user', JSON.stringify(data.user));
      // Remove guest tokens to ensure clean real user session
      localStorage.removeItem('guest_token');
      localStorage.removeItem('guest_user');
      console.log('[OAuth] Google login successful');

      // Check if there's a pending invite token to join tour
      // Try localStorage first, then fallback to URL parameter
      let pendingInviteToken = localStorage.getItem('pendingInviteToken');
      console.log('[OAuth] pendingInviteToken from localStorage:', pendingInviteToken ? pendingInviteToken.substring(0, 20) + '...' : 'none');
      
      // If no token in localStorage, try to get from URL (in case of race condition)
      if (!pendingInviteToken) {
        const params = new URLSearchParams(window.location.search);
        const urlToken = params.get('token');
        if (urlToken) {
          pendingInviteToken = urlToken;
          localStorage.setItem('pendingInviteToken', urlToken);
          console.log('[OAuth] Using token from URL params:', urlToken.substring(0, 20) + '...');
        }
      }
      
      if (pendingInviteToken) {
        try {
          const joinRes = 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 }),
          });
          const joinData = await joinRes.json().catch(() => ({}));
          if (joinRes.ok) {
            localStorage.removeItem('pendingInviteToken');
            if (onLoginSuccess) {
              onLoginSuccess(data.user);
            }
            onClose();
          } else {
            // If invitation is invalid/expired, clear it and redirect to dashboard
            console.log('[OAuth] Token invalid or expired, clearing and redirecting to dashboard');
            localStorage.removeItem('pendingInviteToken');
            if (onLoginSuccess) {
              onLoginSuccess(data.user);
            }
            onClose();
          }
        } catch (joinErr: any) {
          console.error('[OAuth] Join tour after login failed:', joinErr);
          localStorage.removeItem('pendingInviteToken');
          // Still redirect to dashboard on error
          if (onLoginSuccess) {
            onLoginSuccess(data.user);
          }
          onClose();
        }
      } else {
        // Regular login - no auto-join for tour
        if (onLoginSuccess) {
          onLoginSuccess(data.user);
        }
        onClose();
      }
    } catch (err: any) {
      console.error('[OAuth] Login error:', err);
      setError(err.message);
      setIsLoading(false);
    }
  };

  const handleNativeGoogleLogin = async () => {
    setError('');
    setIsLoading(true);
    try {
      const user = await GoogleAuth.signIn();
      console.log('[Native OAuth] 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 nhập Google thất bại');
      }

      localStorage.setItem('token', data.access_token);
      localStorage.setItem('user', JSON.stringify(data.user));
      localStorage.removeItem('guest_token');
      localStorage.removeItem('guest_user');
      console.log('[Native OAuth] Google login successful');

      let pendingInviteToken = localStorage.getItem('pendingInviteToken');
      if (pendingInviteToken) {
        try {
          const joinRes = 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 }),
          });
          if (joinRes.ok) {
            localStorage.removeItem('pendingInviteToken');
          }
        } catch (joinErr) {
          console.error('[Native OAuth] Join tour after login failed:', joinErr);
        }
      }
      
      if (onLoginSuccess) {
        onLoginSuccess(data.user);
      }
      onClose();
    } catch (err: any) {
      console.error('[Native OAuth] Error:', err);
      if (err?.message !== 'Sign in window was closed' && err?.message !== '12501') {
        setError(err.message || 'Đăng nhập Google thất bại');
      }
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (!isOpen || 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-login'),
            { theme: 'outline', size: 'large', width: '380' }
          );
        } catch (e) {
          console.error('Lỗi khởi tạo Google Sign-in:', e);
        }
      }
    }, 100);

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

  if (!isOpen) return null;

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

    try {
      const response = await fetch(`/api/v1/auth/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });

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

      // Lưu phiên đăng nhập
      localStorage.setItem('token', data.access_token);
      localStorage.setItem('user', JSON.stringify(data.user));
      localStorage.removeItem('guest_token');
      localStorage.removeItem('guest_user');
      console.log('[LoginModal] Email/password login successful');

      // Regular login - no auto-join for tour
      if (onLoginSuccess) {
        onLoginSuccess(data.user);
      }
      onClose();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">
      {/* Backdrop */}
      <div 
        className="absolute inset-0 bg-gray-900/60 backdrop-blur-sm animate-in fade-in duration-300"
        onClick={onClose}
      />
      
      {/* Modal Content */}
      <div className="relative w-full sm:max-w-md bg-[var(--surface)] rounded-t-2xl sm:rounded-3xl shadow-2xl overflow-hidden sm:max-h-[85vh] flex flex-col h-full animate-in zoom-in-95 duration-300">
        <div className="p-8 sm:p-10 flex-1 overflow-y-auto">
          <div className="flex justify-between items-start mb-8">
            <div>
              <h2 className="text-3xl font-bold text-[var(--text-primary)]">Đăng nhập</h2>
              <p className="text-[var(--text-secondary)] mt-2">Chào mừng bạn quay trở lại!</p>
            </div>
            <button 
              onClick={onClose}
              className="p-2 hover:bg-[var(--background)] rounded-full transition-colors text-[var(--text-muted)] hover:text-[var(--text-secondary)]"
            >
              <X className="w-6 h-6" />
            </button>
          </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-6" onSubmit={handleSubmit}>
            <div className="space-y-2">
              <label className="text-sm font-semibold text-[var(--text-secondary)] ml-1">Tài khoản hoặc 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 
                  type="text" 
                  placeholder="admin hoặc email..."
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                  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-2">
              <div className="flex justify-between items-center px-1">
                <label className="text-sm font-semibold text-[var(--text-secondary)]">Mật khẩu</label>
                <button className="text-xs font-bold text-blue-600 hover:text-blue-700">Quên mật khẩu?</button>
              </div>
              <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 
                  type="password" 
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  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>

            <button 
              type="submit"
              disabled={isLoading}
              className="w-full flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 text-white font-bold py-4 rounded-2xl shadow-lg shadow-blue-200 transition-all active:scale-[0.98] disabled:opacity-50"
            >
              {isLoading ? 'Đang xử lý...' : 'Đăng nhập'}
              {isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : <ArrowRight className="w-5 h-5" />}
            </button>
          </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 nhập bằng Google
            </button>
          ) : (
            <div id="google-signin-btn-login" className="w-full flex justify-center"></div>
          )}

          <div className="mt-10 pt-8 border-t border-[var(--border)] text-center">
            <p className="text-[var(--text-secondary)]">
              Chưa có tài khoản?{' '}
              <button 
                onClick={() => { onClose(); onSwitchToSignup?.(); }}
                className="font-bold text-blue-600 hover:underline"
              >
                Tạo tài khoản ngay
              </button>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};