import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useStore } from '../store/useStore';
import { authApi, familyApi, inviteLinkApi } from '../api/client';
import { Users, LogOut, Settings, Plus, Loader2, Eye, EyeOff } from 'lucide-react';

export default function NoFamily() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { user, logout, setUser } = useStore();

  const [familyName, setFamilyName] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [joiningFamily, setJoiningFamily] = useState(false);

  useEffect(() => {
    checkPendingInvite();
  }, []);

  const checkPendingInvite = async () => {
    const pendingToken = localStorage.getItem('pendingInviteToken');
    if (!pendingToken) return;

    localStorage.removeItem('pendingInviteToken');

    try {
      setJoiningFamily(true);
      const response = await inviteLinkApi.join(pendingToken);
      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('noFamily.invalidInvite'));
      } else {
        setError(t('noFamily.joinError'));
      }
    } finally {
      setJoiningFamily(false);
    }
  };

  const handleLogout = async () => {
    try {
      await authApi.logout();
      logout();
    } catch (err) {
      console.error(err);
      logout();
    }
  };

  const handleGoToAdmin = () => {
    navigate('/adminpanel');
  };

  const handleCreateFamily = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!familyName.trim()) {
      setError(t('noFamily.enterFamilyName'));
      return;
    }

    try {
      setLoading(true);
      setError('');

      const response = await familyApi.createMyFamily({
        name: familyName.trim(),
        password: password || undefined,
      });

      setUser({
        ...user!,
        family_id: response.data.family_id,
      });

      navigate(`/family/${response.data.family_id}`);
    } catch (err: unknown) {
      if (err && typeof err === 'object' && 'response' in err) {
        const axiosError = err as { response?: { status?: number } };
        if (axiosError.response?.status === 409) {
          setError(t('noFamily.alreadyInFamily'));
        } else {
          setError(t('noFamily.createError'));
        }
      } else {
        setError(t('noFamily.createError'));
      }
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  if (joiningFamily) {
    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('noFamily.joiningFamily')}</span>
        </div>
      </div>
    );
  }

  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-6">
            <div className="p-4 bg-linear-to-br from-purple-500 to-blue-500 text-white rounded-2xl mb-4 shadow-lg">
              <Users className="w-12 h-12" />
            </div>
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-900 mb-2">
              {t('noFamily.welcome')}
            </h1>
            <p className="text-gray-600">
              <span className="font-semibold text-purple-600">{user?.email || user?.username}</span>
            </p>
          </div>

          <form onSubmit={handleCreateFamily} className="mb-6">
            <h2 className="text-lg font-semibold text-gray-800 mb-4 text-center">
              {t('noFamily.createFamily')}
            </h2>

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

            <div className="space-y-4">
              <div>
                <label htmlFor="familyName" className="block text-sm font-medium text-gray-700 mb-1">
                  {t('noFamily.familyNameRequired')}
                </label>
                <input
                  type="text"
                  id="familyName"
                  value={familyName}
                  onChange={(e) => setFamilyName(e.target.value)}
                  placeholder={t('noFamily.familyNamePlaceholder')}
                  className="w-full px-4 py-3 border-2 border-gray-300 rounded-xl focus:border-purple-500 focus:outline-none transition-colors"
                  disabled={loading}
                />
              </div>

              <div>
                <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
                  {t('noFamily.password')} <span className="text-gray-400">{t('noFamily.passwordOptional')}</span>
                </label>
                <div className="relative">
                  <input
                    type={showPassword ? 'text' : 'password'}
                    id="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder={t('noFamily.passwordPlaceholder')}
                    className="w-full px-4 py-3 pr-12 border-2 border-gray-300 rounded-xl focus:border-purple-500 focus:outline-none transition-colors"
                    disabled={loading}
                  />
                  <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 ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                  </button>
                </div>
                <p className="mt-1 text-xs text-gray-500">
                  {t('noFamily.passwordHint')}
                </p>
              </div>

              <button
                type="submit"
                disabled={loading || !familyName.trim()}
                className="w-full flex items-center justify-center gap-2 px-6 py-4 bg-linear-to-r from-purple-600 to-blue-600 text-white rounded-2xl hover:shadow-xl transition-all duration-300 font-semibold disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {loading ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <>
                    <Plus className="w-5 h-5" />
                    {t('noFamily.createButton')}
                  </>
                )}
              </button>
            </div>
          </form>

          <div className="border-t border-gray-200 pt-6">
            <div className="flex flex-col gap-3">
              {user?.is_admin && (
                <button
                  onClick={handleGoToAdmin}
                  className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-2xl transition-all duration-300 font-medium"
                >
                  <Settings className="w-5 h-5" />
                  {t('noFamily.adminPanel')}
                </button>
              )}
              <button
                onClick={handleLogout}
                className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-2xl transition-all duration-300 font-medium"
              >
                <LogOut className="w-5 h-5" />
                {t('common.logout')}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
