import { useState, useEffect } from "react";
import { Settings } from "../../lib/settings";
import Header from "../navigation/Header";
import LoginForm from "./LoginForm";
import { LogoutContext } from "../../lib/LogoutContext";
import { RefreshContext } from "../../lib/RefreshContext";
import TabView from "../TabView";

export default function AuthWrapper() {
  const [isConfigured, setIsConfigured] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [lastUpdate, setLastUpdate] = useState(Date.now());

  useEffect(() => {
    async function checkConfiguration() {
      try {
        const serviceUrl = await Settings.getServiceUrl();
        const adminPassword = await Settings.getAdminPassword();
        setIsConfigured(Boolean(serviceUrl && adminPassword));
      } catch (error) {
        console.error("Error checking configuration:", error);
        setIsConfigured(false);
      } finally {
        setIsLoading(false);
      }
    }
    checkConfiguration();
  }, [lastUpdate]);

  const handleLogout = async () => {
    try {
      await Settings.clearSettings();
      setIsConfigured(false);
    } catch (error) {
      console.error("Error during logout:", error);
    }
  };

  const refresh = () => {
    setLastUpdate(Date.now());
  };

  if (isLoading) {
    return (
      <div className="w-full h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900" />
      </div>
    );
  }

  if (!isConfigured) {
    return <LoginForm onLogin={() => setIsConfigured(true)} />;
  }

  return (
    <LogoutContext.Provider value={handleLogout}>
      <RefreshContext.Provider value={{ refresh, lastUpdate }}>
        <div className="w-full flex flex-col">
          <Header />
          <div className="min-h-[calc(100vh-64px-52px)] p-2 sm:p-4">
            <div className="container mx-auto max-w-full">
              <TabView />
            </div>
          </div>
        </div>
      </RefreshContext.Provider>
    </LogoutContext.Provider>
  );
}
