import { useQuery, useQueryClient } from '@tanstack/react-query';
import { FormEvent, ReactNode, useCallback, useContext, useEffect, useState, createContext } from 'react';
import { api } from '../../api/client';
import { clearAccessToken, getAccessToken, PLATFORM_UNAUTHORIZED_EVENT, PlatformSession, setAccessToken } from './session';

type AuthContextValue = {
  session: PlatformSession;
  logout: () => void;
};

const AuthContext = createContext<AuthContextValue | null>(null);

export function usePlatformSession() {
  const value = useContext(AuthContext);
  if (!value) throw new Error('usePlatformSession must be used inside AuthGate');
  return value;
}

export function AuthGate({ children }: { children: ReactNode }) {
  const queryClient = useQueryClient();
  const [tokenVersion, setTokenVersion] = useState(0);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [draftToken, setDraftToken] = useState('');
  const [legacyMode, setLegacyMode] = useState(false);
  const [attempted, setAttempted] = useState(() => Boolean(getAccessToken()));
  const [loginPending, setLoginPending] = useState(false);
  const [loginError, setLoginError] = useState('');
  const session = useQuery({
    queryKey: ['platform-session', tokenVersion],
    queryFn: ({ signal }) => api.session(signal),
    retry: false,
    staleTime: Infinity
  });
  const clearClientSession = useCallback(() => {
    void queryClient.cancelQueries();
    queryClient.clear();
  }, [queryClient]);
  const finishLogout = useCallback(() => {
    clearAccessToken();
    clearClientSession();
    setPassword('');
    setDraftToken('');
    setAttempted(false);
    setLoginError('');
    setTokenVersion((value) => value + 1);
  }, [clearClientSession]);
  const logout = useCallback(() => {
    void api.logout().catch(() => undefined).finally(finishLogout);
  }, [finishLogout]);
  useEffect(() => {
    window.addEventListener(PLATFORM_UNAUTHORIZED_EVENT, finishLogout);
    return () => window.removeEventListener(PLATFORM_UNAUTHORIZED_EVENT, finishLogout);
  }, [finishLogout]);

  const login = async (event: FormEvent) => {
    event.preventDefault();
    setAttempted(true);
    setLoginError('');
    setLoginPending(true);
    try {
      if (legacyMode) {
        setAccessToken(draftToken);
      } else {
        const result = await api.login({ username: username.trim(), password });
        setAccessToken(result.accessToken);
      }
      clearClientSession();
      setTokenVersion((value) => value + 1);
    } catch (error) {
      clearAccessToken();
      setLoginError(error instanceof Error ? error.message : '登录失败，请稍后重试');
    } finally {
      setLoginPending(false);
    }
  };

  if (session.isPending) {
    return <div className="v2-auth-screen"><div className="v2-auth-card v2-auth-loading"><img className="v2-auth-logo" src="/brand-logo.svg" alt="羚牛智能" /><i className="v2-auth-spinner" /><strong>正在验证登录状态…</strong></div></div>;
  }
  if (!session.data) {
    const error = loginError || (attempted && session.error ? session.error.message : '');
    return <div className="v2-auth-screen">
      <section className="v2-auth-intro" aria-hidden="true">
        <img src="/brand-logo.svg" alt="" />
        <h2>让每一辆车的数据<br />清晰、可控、可信</h2>
        <p>统一查看实时状态、车辆轨迹与里程数据。账号权限由管理员按车辆和功能精确分配。</p>
        <div><span>车辆级数据隔离</span><span>登录审计</span><span>可扩展身份接入</span></div>
      </section>
      <form className="v2-auth-card" onSubmit={login}>
        <img className="v2-auth-logo" src="/brand-logo.svg" alt="羚牛智能" />
        <h1>登录车辆数据中台</h1>
        <p>{legacyMode ? '仅供平台运维使用，输入服务器访问令牌。' : '使用管理员为你开通的账号登录。'}</p>
        {legacyMode ? <label><span>运维访问令牌</span><input autoFocus required type="password" autoComplete="off" value={draftToken} onChange={(event) => setDraftToken(event.target.value)} placeholder="Bearer token" /></label> : <>
          <label><span>用户名</span><input autoFocus required autoComplete="username" value={username} onChange={(event) => setUsername(event.target.value)} placeholder="请输入用户名" /></label>
          <label><span>密码</span><input required type="password" autoComplete="current-password" value={password} onChange={(event) => setPassword(event.target.value)} placeholder="请输入密码" /></label>
        </>}
        {error ? <em role="alert">{error}</em> : null}
        <button type="submit" disabled={loginPending || (legacyMode ? !draftToken.trim() : !username.trim() || !password)}>{loginPending ? '正在登录…' : '登录'}</button>
        <button className="v2-auth-mode-switch" type="button" onClick={() => { setLegacyMode((value) => !value); setLoginError(''); }}>
          {legacyMode ? '返回账号密码登录' : '使用运维令牌登录'}
        </button>
        <small>登录即表示你同意遵守平台数据安全规范</small>
      </form>
    </div>;
  }
  return <AuthContext.Provider value={{ session: session.data, logout }}>{children}</AuthContext.Provider>;
}
