import { useCallback, useEffect, useState } from 'react';
import { apiGitHub } from '../api';

export function useGitHubConnection() {
  const [connected, setConnected] = useState(false);
  const [githubLogin, setGithubLogin] = useState('');
  const [canDeleteRepos, setCanDeleteRepos] = useState(false);
  const [connecting, setConnecting] = useState(false);
  const [error, setError] = useState('');
  const [message, setMessage] = useState('');

  const refresh = useCallback(async () => {
    try {
      const st = await apiGitHub.status();
      setConnected(!!st.connected);
      setGithubLogin(st.githubLogin || '');
      setCanDeleteRepos(!!st.canDeleteRepos);
    } catch (e) {
      console.error(e);
      setConnected(false);
      setGithubLogin('');
      setCanDeleteRepos(false);
    }
  }, []);

  useEffect(() => {
    refresh().catch(console.error);
  }, [refresh]);

  useEffect(() => {
    const onMessage = (e: MessageEvent) => {
      const data = e.data as { type?: string; ok?: boolean; detail?: string };
      if (data?.type !== 'simple-care-github-connected') return;
      setConnecting(false);
      if (data.ok) {
        refresh().catch(console.error);
        setMessage(typeof data.detail === 'string' ? `Đã kết nối GitHub @${data.detail}` : 'Đã kết nối GitHub');
        setError('');
      } else {
        setError(typeof data.detail === 'string' ? data.detail : 'Kết nối GitHub thất bại');
      }
    };
    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
  }, [refresh]);

  const connect = async () => {
    setError('');
    setMessage('');
    setConnecting(true);
    try {
      const { authorizeUrl } = await apiGitHub.authorizeUrl();
      const w = window.open(authorizeUrl, 'simple_care_github_oauth', 'width=720,height=760');
      if (!w) {
        setConnecting(false);
        setError('Trình duyệt chặn popup — cho phép popup rồi thử lại.');
      }
    } catch (e: any) {
      setConnecting(false);
      setError(e?.message || 'Không mở được OAuth GitHub');
    }
  };

  const disconnect = async () => {
    setError('');
    setMessage('');
    try {
      await apiGitHub.disconnect();
      setConnected(false);
      setGithubLogin('');
      setCanDeleteRepos(false);
      setMessage('Đã ngắt kết nối GitHub');
    } catch (e: any) {
      setError(e?.message || 'Ngắt kết nối thất bại');
    }
  };

  return {
    connected,
    githubLogin,
    canDeleteRepos,
    connecting,
    error,
    message,
    setError,
    setMessage,
    refresh,
    connect,
    disconnect,
  };
}
