import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { authApi } from '../api/client';
import { useStore } from '../store/useStore';
import { Loader2, Wallet } from 'lucide-react';
import { FcGoogle } from 'react-icons/fc';

const isTauriEnv = () => typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;

const DEEP_LINK_SCHEME = 'com.arrelin.family-budget-android://auth';

export default function Login() {
  const { t } = useTranslation();
  const { setUser } = useStore();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!isTauriEnv()) return;

    let unlisten: (() => void) | null = null;

    const setupDeepLink = async () => {
      const { onOpenUrl } = await import('@tauri-apps/plugin-deep-link');
      unlisten = await onOpenUrl(async (urls) => {
        const url = Array.isArray(urls) ? urls[0] : urls;
        if (!url.startsWith(DEEP_LINK_SCHEME)) return;

        const token = new URL(url).searchParams.get('token');
        if (!token) return;

        try {
          setLoading(true);
          await authApi.mobileCallback(token);
          const me = await authApi.me();
          setUser(me.data);
        } catch {
          setError(t('login.authError'));
          setLoading(false);
        }
      });
    };

    setupDeepLink();
    return () => { unlisten?.(); };
  }, []);

  const handleGoogleLogin = async () => {
    try {
      setLoading(true);
      setError('');

      if (isTauriEnv()) {
        const { open } = await import('@tauri-apps/plugin-shell');
        const response = await authApi.getGoogleAuthUrl(undefined, true);
        await open(response.data.url);
        return;
      }

      const currentUrl = window.location.origin;
      const response = await authApi.getGoogleAuthUrl(currentUrl);
      window.location.href = response.data.url;
    } catch (err) {
      setError(t('login.authError'));
      console.error(err);
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen gradient-bg flex items-center justify-center px-4">
      <div className="w-full max-w-md">
        <div className="glass-effect rounded-3xl shadow-2xl p-8 sm:p-10">
          <div className="flex flex-col items-center text-center mb-8">
            <div className="p-4 category-icon text-white rounded-2xl mb-4 shadow-lg">
              <Wallet className="w-12 h-12" />
            </div>
            <h1 className="text-3xl sm:text-4xl font-bold text-gray-900 mb-2">
              {t('login.title')}
            </h1>
            <p className="text-gray-600">
              {t('login.subtitle')}
            </p>
          </div>

          {error && (
            <div className="mb-6 p-4 bg-red-100 border-l-4 border-red-500 text-red-700 rounded-xl">
              <span className="text-sm font-medium">{error}</span>
            </div>
          )}

          <button
            onClick={handleGoogleLogin}
            disabled={loading}
            className="w-full flex items-center justify-center gap-3 px-6 py-4 bg-white border-2 border-gray-300 rounded-2xl hover:bg-gray-50 hover:border-gray-400 transition-all duration-300 font-semibold text-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? (
              <Loader2 className="w-6 h-6 animate-spin" />
            ) : (
              <>
                <FcGoogle className="w-6 h-6" />
                {t('login.googleButton')}
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
