import { Text, View, ScrollView } from "react-native";
import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context';
import { useState, useEffect } from "react";
import { useRouter } from "expo-router";

import LoginForm from "./components/LoginForm";
import LogoutButton from "./components/LogoutButton";
import EnvironmentCard from "./components/EnvironmentCard";

import { AuthProvider } from "./context/AuthContext";
import { useAuth } from "./context/AuthContext";

interface Environment {
  Name: string;
  PublicURL: string;
  Status: number;
  URL: string;
  Id: number;
}

export default function Index() {
  return (

    <AuthProvider>
      <View style={{ flex: 1, padding: 16, width: '100%' }}>
        <MainContent />
      </View>
    </AuthProvider>
  );
}

function MainContent() {
  const router = useRouter();
  const { isAuthenticated, domain, username, authData } = useAuth();
  const [environmentData, setEnvironmentData] = useState<Environment[] | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchEnvironmentData = async () => {
      if (!isAuthenticated) return;
      
      setIsLoading(true);
      try {
        const response = await fetch('https://portainer.evansteele.net/api/endpoints', {
          headers: {
            'Authorization': `Bearer ${authData.jwt}`
          }
        });
        const data = await response.json();
        setEnvironmentData(data);
      } catch (err : any) {
        setError(err.message);
      } finally {
        setIsLoading(false);
      }
    };

    fetchEnvironmentData();
  }, [isAuthenticated]);

  if (!isAuthenticated) {
    return (
      <View style={{ flex: 1, padding: 16, width: '100%' }}>
        <LoginForm />
      </View>
    );
  }

  return (
    <SafeAreaProvider>
      <SafeAreaView style={{ flex: 1, padding: 16, width: '100%' }}>
        <ScrollView showsVerticalScrollIndicator={false}>
          {environmentData && environmentData.map((environment, index) => (
            <EnvironmentCard
              key={index}
              name={environment.Name}
              publicUrl={environment.PublicURL}
              status={environment.Status}
              url={environment.URL}
              id={environment.Id}
              onPress={() => router.push({
                pathname: `/envs/[env]`,
                params: { env: environment.Id }
              })}
            />
          ))}
        </ScrollView>
      </SafeAreaView>
      <LogoutButton />
    </SafeAreaProvider>
  );
}
