import { useState, useEffect } from 'react';
import { LogIn, Building2, User, Lock, Loader2 } from 'lucide-react';
import { comms } from '@/communication';
import { UserGroup } from '@/types';

interface LoginProps {
  onLoginSuccess: () => void;
}

export function Login({ onLoginSuccess }: LoginProps) {
  const [groups, setGroups] = useState<UserGroup[]>([]);
  const [gcode, setGcode] = useState('');
  const [userId, setUserId] = useState('');
  const [password, setPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [initialLoading, setInitialLoading] = useState(true);

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

  const loadInitialData = async () => {
    try {
      // 그룹 목록 및 이전 로그인 정보 로드
      const [groupsData, prevInfo] = await Promise.all([
        comms.getUserGroups(),
        comms.getPreviousLoginInfo()
      ]);

      console.log('[Login] 부서 목록:', groupsData);
      setGroups(groupsData);

      if (prevInfo.Success && prevInfo.Data) {
        if (prevInfo.Data.LastGcode) {
          setGcode(prevInfo.Data.LastGcode);
        }
        if (prevInfo.Data.LastId) {
          setUserId(prevInfo.Data.LastId);
          setRememberMe(true);
        }
      }
    } catch (err) {
      console.error('초기 데이터 로드 실패:', err);
    } finally {
      setInitialLoading(false);
    }
  };

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

    try {
      const result = await comms.login(gcode, userId, password, rememberMe);

      if (result.Success) {
        if (result.VersionWarning) {
          alert(result.VersionWarning);
        }
        onLoginSuccess();
      } else {
        setError(result.Message || '로그인에 실패했습니다.');
      }
    } catch (err) {
      setError('서버 연결에 실패했습니다.');
      console.error('로그인 오류:', err);
    } finally {
      setLoading(false);
    }
  };

  if (initialLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <Loader2 className="w-8 h-8 text-white animate-spin" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo */}
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold text-white mb-2">GroupWare</h1>
          <p className="text-white/60">ATK4-EET</p>
        </div>

        {/* Login Form */}
        <div className="glass-effect rounded-2xl p-8">
          <h2 className="text-xl font-semibold text-white mb-6 text-center">로그인</h2>

          <form onSubmit={handleSubmit} className="space-y-5">
            {/* 부서 선택 */}
            <div>
              <label className="block text-sm font-medium text-white/70 mb-2">
                소속 부서
              </label>
              <div className="relative">
                <Building2 className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-white/50" />
                <select
                  value={gcode}
                  onChange={(e) => setGcode(e.target.value)}
                  className="w-full bg-white/10 border border-white/20 rounded-xl pl-10 pr-4 py-3 text-white focus:outline-none focus:border-primary-400 appearance-none"
                  required
                >
                  <option value="">부서를 선택하세요</option>
                  {groups.filter(g => g.gcode).map((group) => (
                    <option key={group.gcode} value={group.gcode}>
                      {group.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* 사용자 ID */}
            <div>
              <label className="block text-sm font-medium text-white/70 mb-2">
                사용자 ID
              </label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-white/50" />
                <input
                  type="text"
                  value={userId}
                  onChange={(e) => setUserId(e.target.value)}
                  className="w-full bg-white/10 border border-white/20 rounded-lg pl-10 pr-4 py-3 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  placeholder="ID를 입력하세요"
                  required
                />
              </div>
            </div>

            {/* 비밀번호 */}
            <div>
              <label className="block text-sm font-medium text-white/70 mb-2">
                비밀번호
              </label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-white/50" />
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full bg-white/10 border border-white/20 rounded-lg pl-10 pr-4 py-3 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  placeholder="비밀번호를 입력하세요"
                  required
                />
              </div>
            </div>

            {/* 로그인 정보 저장 */}
            <div className="flex items-center">
              <input
                type="checkbox"
                id="rememberMe"
                checked={rememberMe}
                onChange={(e) => setRememberMe(e.target.checked)}
                className="w-4 h-4 rounded border-white/20 bg-white/10 text-primary-500 focus:ring-primary-500"
              />
              <label htmlFor="rememberMe" className="ml-2 text-sm text-white/70">
                로그인 정보 저장
              </label>
            </div>

            {/* 에러 메시지 */}
            {error && (
              <div className="bg-danger-500/20 border border-danger-500/50 rounded-lg px-4 py-3 text-danger-300 text-sm">
                {error}
              </div>
            )}

            {/* 로그인 버튼 */}
            <button
              type="submit"
              disabled={loading}
              className="w-full bg-primary-500 hover:bg-primary-600 disabled:bg-primary-500/50 text-white font-medium py-3 rounded-lg transition-colors flex items-center justify-center space-x-2"
            >
              {loading ? (
                <Loader2 className="w-5 h-5 animate-spin" />
              ) : (
                <>
                  <LogIn className="w-5 h-5" />
                  <span>로그인</span>
                </>
              )}
            </button>
          </form>
        </div>

        {/* Footer */}
        <p className="text-center text-white/40 text-sm mt-6">
          © 2024 GroupWare. All rights reserved.
        </p>
      </div>
    </div>
  );
}
