"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { MiniKit } from "@worldcoin/minikit-js";
import { useTranslation } from "react-i18next";
import TabBar from "@/components/TabBar";

export default function Dashboard() {
  const [username, setUsername] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const router = useRouter();
  const { t } = useTranslation('common');

  useEffect(() => {
    const walletAddress = localStorage.getItem("walletAddress");
    
    // Redirect to login if not authenticated
    if (!walletAddress) {
      router.push("/");
      return;
    }

    // Get user info from MiniKit
    const getUserInfo = async () => {
      try {
        const minikit = MiniKit.instance;
        if (!minikit) {
          console.error("MiniKit not initialized");
          return;
        }

        const profile = await minikit.commandsAsync.getProfile();
        // Maintain original MiniKit username display behavior
        if (profile.username) {
          setUsername(profile.username);
          // We directly use the username as provided by MiniKit without modification
          // This ensures we preserve the exact format as returned by the MiniKit API
        }
      } catch (err) {
        console.error("Failed to get user profile:", err);
      } finally {
        setLoading(false);
      }
    };

    getUserInfo();
  }, [router]);

  return (
    <main className="flex min-h-screen flex-col items-center p-4 pb-20">
      <div className="w-full max-w-md">
        <div className="bg-white rounded-lg shadow-md p-6 mb-4">
          <h1 className="text-2xl font-bold text-center mb-4">
            {t('dashboard')}
          </h1>
          
          {loading ? (
            <p className="text-center">Loading...</p>
          ) : (
            <>
              <div className="mb-6 p-4 bg-secondary rounded-lg">
                <h2 className="text-xl font-bold text-center text-primary">
                  {t('welcome_user', { username: username || 'User' })}
                </h2>
              </div>
              
              <div className="border border-gray-200 rounded-lg p-4">
                <h3 className="font-medium mb-2">
                  {t('write_your_app_here')}
                </h3>
                <p className="text-gray-600 text-sm">
                  This is your dashboard. Use this as a starting point to build your application.
                </p>
              </div>
            </>
          )}
        </div>
      </div>
      
      <TabBar />
    </main>
  );
}
