import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { inviteLinkApi, authApi } from '../api/client';
import { useStore } from '../store/useStore';
import { Loader2, Users, UserPlus, AlertCircle } from 'lucide-react';

export default function InvitePage() {
  const { t } = useTranslation();
  const { token } = useParams<{ token: string }>();
  const navigate = useNavigate();
  const { isAuthenticated, setUser } = useStore();

  const [loading, setLoading] = useState(true);
  const [joining, setJoining] = useState(false);
  const [error, setError] = useState('');
  const [familyName, setFamilyName] = useState<string | null>(null);
  const [isValid, setIsValid] = useState(false);

  useEffect(() => {
    if (token) {
      validateInvite();
    }
  }, [token]);

  useEffect(() => {
    if (isAuthenticated && isValid && token) {
      joinFamily();
    }
  }, [isAuthenticated, isValid]);

  const validateInvite = async () => {
    if (!token) return;

    try {
      setLoading(true);
      const response = await inviteLinkApi.validate(token);
      if (response.data.valid) {
        setIsValid(true);
        setFamilyName(response.data.family_name);
      } else {
        setError(t('invite.invalid'));
      }
    } catch (err) {
      setError(t('invite.notFound'));
    } finally {
      setLoading(false);
    }
  };

  const joinFamily = async () => {
    if (!token) return;

    try {
      setJoining(true);
      const response = await inviteLinkApi.join(token);
      if (response.data.success) {
        const meResponse = await authApi.me();
        setUser(meResponse.data);
        navigate(`/family/${response.data.family_id}`);
      } else {
        setError(response.data.message);
      }
    } catch (err: any) {
      if (err.response?.status === 400) {
        setError(t('invite.alreadyInFamily'));
      } else {
        setError(t('invite.joinError'));
      }
    } finally {
      setJoining(false);
    }
  };

  const handleGoogleLogin = async () => {
    if (token) {
      localStorage.setItem('pendingInviteToken', token);
    }
    try {
      const response = await authApi.getGoogleAuthUrl(window.location.href);
      window.location.href = response.data.url;
    } catch (err) {
      setError(t('login.authError'));
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center gradient-bg">
        <div className="flex items-center gap-3 text-white">
          <Loader2 className="w-8 h-8 animate-spin" />
          <span className="text-xl font-medium">{t('invite.validating')}</span>
        </div>
      </div>
    );
  }

  if (joining) {
    return (
      <div className="min-h-screen flex items-center justify-center gradient-bg">
        <div className="flex items-center gap-3 text-white">
          <Loader2 className="w-8 h-8 animate-spin" />
          <span className="text-xl font-medium">{t('invite.joining')}</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center gradient-bg px-4">
        <div className="glass-effect rounded-3xl shadow-2xl p-8 max-w-md w-full text-center">
          <div className="p-4 btn-danger rounded-2xl inline-block mb-6">
            <AlertCircle className="w-12 h-12 text-white" />
          </div>
          <h1 className="text-2xl font-bold text-gray-800 mb-4">{t('common.error')}</h1>
          <p className="text-gray-600 mb-6">{error}</p>
          <button
            onClick={() => navigate('/')}
            className="px-6 py-3 btn-primary text-white rounded-2xl font-semibold hover:shadow-xl transition-all"
          >
            {t('common.toHome')}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center gradient-bg px-4">
      <div className="glass-effect rounded-3xl shadow-2xl p-8 max-w-md w-full text-center">
        <div className="p-4 category-icon rounded-2xl inline-block mb-6">
          <Users className="w-12 h-12 text-white" />
        </div>
        <h1 className="text-2xl font-bold text-gray-800 mb-2">
          {t('invite.pageTitle')}
        </h1>
        <p className="text-3xl font-bold text-gray-800 mb-6">
          {familyName}
        </p>
        <p className="text-gray-600 mb-8">
          {t('invite.pageDescription')}
        </p>
        <button
          onClick={handleGoogleLogin}
          className="w-full flex items-center justify-center gap-3 px-6 py-4 btn-primary text-white rounded-2xl font-semibold hover:shadow-xl transition-all"
        >
          <UserPlus className="w-5 h-5" />
          {t('invite.loginAndJoin')}
        </button>
      </div>
    </div>
  );
}
