import { useState, useEffect } from "react";
import { Box, Text, useInput } from "ink";
import { getAuthStatus, login, isGhInstalled } from "../../github/auth.ts";

export interface GitHubAuthStepProps {
  onComplete: (auth: { authenticated: boolean; user?: string; skipped: boolean }) => void;
  onBack: () => void;
  onCancel: () => void;
}

type AuthStatus = "checking" | "authenticated" | "not_authenticated" | "gh_not_installed" | "login_failed";

export function GitHubAuthStep({ onComplete, onBack, onCancel }: GitHubAuthStepProps) {
  const [status, setStatus] = useState<AuthStatus>("checking");
  const [user, setUser] = useState<string | undefined>();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

  const checkAuth = async () => {
    setStatus("checking");
    setError(null);

    const ghInstalled = await isGhInstalled();

    if (!ghInstalled) {
      setStatus("gh_not_installed");
      return;
    }

    try {
      const authStatus = await getAuthStatus();
      if (authStatus.authenticated) {
        setStatus("authenticated");
        setUser(authStatus.user);
      } else {
        setStatus("not_authenticated");
      }
    } catch {
      setStatus("not_authenticated");
    }
  };

  const handleLogin = async () => {
    setLoading(true);
    setError(null);

    try {
      const result = await login();
      if (result.success) {
        setStatus("authenticated");
        setUser(result.user);
      } else {
        setStatus("login_failed");
        setError(result.error || "Login failed");
      }
    } catch {
      setStatus("login_failed");
      setError("An unexpected error occurred");
    } finally {
      setLoading(false);
    }
  };

  useInput((input, key) => {
    if (loading) return;

    if (key.escape || input === "q" || input === "Q") {
      onCancel();
      return;
    }

    if (key.backspace || key.delete) {
      onBack();
      return;
    }

    if (key.return) {
      // Complete with current auth state
      onComplete({
        authenticated: status === "authenticated",
        user,
        skipped: false,
      });
      return;
    }

    // Login
    if ((input === "l" || input === "L") && (status === "not_authenticated" || status === "login_failed")) {
      handleLogin();
      return;
    }

    // Re-login
    if ((input === "r" || input === "R") && status === "authenticated") {
      handleLogin();
      return;
    }

    // Skip
    if (input === "s" || input === "S") {
      onComplete({
        authenticated: false,
        user: undefined,
        skipped: true,
      });
      return;
    }
  });

  return (
    <Box
      flexDirection="column"
      borderStyle="round"
      borderColor="cyan"
      paddingX={2}
      paddingY={1}
      width={80}
    >
      {/* Title */}
      <Box marginBottom={1}>
        <Text bold color="cyan">
          GitHub Authentication
        </Text>
      </Box>

      {/* Description */}
      <Box marginBottom={1}>
        <Text>GitHub integration is optional but recommended for full functionality.</Text>
      </Box>

      {/* Checking status */}
      {status === "checking" && (
        <Box marginBottom={1}>
          <Text dimColor>Checking authentication status...</Text>
        </Box>
      )}

      {/* Authenticated */}
      {status === "authenticated" && (
        <Box flexDirection="column" marginBottom={1}>
          <Box marginBottom={1}>
            <Text color="green">✓ </Text>
            <Text color="green" bold>
              Authenticated{user ? ` as ${user}` : ""}
            </Text>
          </Box>
          <Text dimColor>You're all set! GitHub features are ready to use.</Text>
        </Box>
      )}

      {/* Not authenticated */}
      {status === "not_authenticated" && !loading && (
        <Box flexDirection="column" marginBottom={1}>
          <Box marginBottom={1}>
            <Text color="yellow">○ </Text>
            <Text color="yellow">Not authenticated</Text>
          </Box>
          <Text dimColor>GitHub CLI (gh) is installed and ready.</Text>
        </Box>
      )}

      {/* gh not installed */}
      {status === "gh_not_installed" && (
        <Box flexDirection="column" marginBottom={1}>
          <Box marginBottom={1}>
            <Text color="red">✗ </Text>
            <Text color="red">GitHub CLI (gh) is not installed</Text>
          </Box>
          <Box flexDirection="column" marginBottom={1}>
            <Text dimColor>To enable GitHub features:</Text>
            <Text dimColor>  1. Install gh CLI from https://cli.github.com</Text>
            <Text dimColor>  2. Run 'gitforest login' to authenticate</Text>
            <Text dimColor>  3. Or set GITHUB_TOKEN environment variable</Text>
          </Box>
        </Box>
      )}

      {/* Login failed */}
      {status === "login_failed" && !loading && (
        <Box flexDirection="column" marginBottom={1}>
          <Box marginBottom={1}>
            <Text color="red">✗ </Text>
            <Text color="red">Authentication failed</Text>
          </Box>
          {error && (
            <Box marginBottom={1}>
              <Text color="red">{error}</Text>
            </Box>
          )}
          <Text dimColor>You can try again or skip for now.</Text>
        </Box>
      )}

      {/* Loading */}
      {loading && (
        <Box marginBottom={1}>
          <Text dimColor>Opening browser for authentication...</Text>
        </Box>
      )}

      {/* Actions */}
      {!loading && status !== "checking" && (
        <Box flexDirection="column" marginTop={1}>
          {status === "not_authenticated" || status === "login_failed" ? (
            <Box gap={2}>
              <Text dimColor>Press </Text>
              <Text color="green" bold>
                l
              </Text>
              <Text dimColor>Login</Text>
              <Text color="green" bold>
                s
              </Text>
              <Text dimColor>Skip</Text>
              <Text color="green" bold>
                Enter
              </Text>
              <Text dimColor>Continue</Text>
            </Box>
          ) : status === "authenticated" ? (
            <Box gap={2}>
              <Text dimColor>Press </Text>
              <Text color="green" bold>
                r
              </Text>
              <Text dimColor>Re-login</Text>
              <Text color="green" bold>
                s
              </Text>
              <Text dimColor>Skip</Text>
              <Text color="green" bold>
                Enter
              </Text>
              <Text dimColor>Continue</Text>
            </Box>
          ) : status === "gh_not_installed" ? (
            <Box gap={2}>
              <Text dimColor>Press </Text>
              <Text color="green" bold>
                s
              </Text>
              <Text dimColor>Skip</Text>
              <Text color="green" bold>
                Enter
              </Text>
              <Text dimColor>Continue</Text>
            </Box>
          ) : null}
          <Box gap={2}>
            <Text dimColor></Text>
            <Text color="red" bold>
              Backspace
            </Text>
            <Text dimColor>Back</Text>
            <Text color="red" bold>
              q
            </Text>
            <Text dimColor>Quit</Text>
          </Box>
        </Box>
      )}
    </Box>
  );
}
