import React, { createContext, useContext, useEffect, useMemo, useState } from "react";
import { fetchMe, loginRequest, setAuthToken } from "../api/client";

interface AuthContextProps {
  user: { username: string } | null;
  token: string | null;
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
  loading: boolean;
}

const AuthContext = createContext<AuthContextProps | undefined>(undefined);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<{ username: string } | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const stored = localStorage.getItem("token");
    if (stored) {
      setAuthToken(stored);
      setToken(stored);
      fetchMe()
        .then((data) => setUser({ username: data.username }))
        .catch(() => {
          setAuthToken(undefined);
          setToken(null);
          setUser(null);
        })
        .finally(() => setLoading(false));
    } else {
      setLoading(false);
    }
  }, []);

  const login = async (username: string, password: string) => {
    const { token: newToken, username: returnedUsername } = await loginRequest(username, password);
    setAuthToken(newToken);
    setToken(newToken);
    setUser({ username: returnedUsername });
  };

  const logout = () => {
    setAuthToken(undefined);
    setToken(null);
    setUser(null);
  };

  const value = useMemo(
    () => ({ user, token, login, logout, loading }),
    [user, token, loading]
  );

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error("useAuth AuthProvider içinde kullanılmalı");
  return ctx;
}
