'use client';

import { useAuthStore } from '@/store/auth-store';
// import { useOnboardingStore } from '@/store/onboarding-store';
import type { User } from '@/types/user';
import { queryClient } from "@/lib/query-client";
import { API_BASE } from '../http';

function generateToken(): string {
  const arr = new Uint8Array(12);
  window.crypto.getRandomValues(arr);
  return Array.from(arr, (v) => v.toString(16).padStart(2, '0')).join('');
}

const user = {
  id: 'USR-000',
  avatar: '/assets/avatar.png',
  firstName: 'Sofia',
  lastName: 'Rivers',
  email: 'sofia@devias.io',
} satisfies User;

export interface SignUpParams {
  firstName: string;
  lastName: string;
  email: string;
  password: string;
}

export interface SignInWithOAuthParams {
  provider: 'google' | 'discord';
}

export interface SignInWithPasswordParams {
  email: string;
  password: string;
}

export interface ForgetPasswordParams {
  email: string;
}
export interface UpdatePasswordParams {
  userId: string;
  password: string;
}

class AuthClient {
  async signUp(_: SignUpParams): Promise<{ error?: string }> {
    // Make API request

    // We do not handle the API, so we'll just generate a token and store it in localStorage.
    const token = generateToken();
    localStorage.setItem('custom-auth-token', token);

    return {};
  }

  async signInWithOAuth(_: SignInWithOAuthParams): Promise<{ error?: string }> {
    return { error: 'Social authentication not implemented' };
  }

  async signInWithPassword(params: SignInWithPasswordParams): Promise<{ error?: string }> {
    const { email, password } = params;

    // Make API request

    // We do not handle the API, so we'll check if the credentials match with the hardcoded ones.
    if (email !== 'sofia@client.io' || password !== 'Secret1') {
      return { error: 'Invalid credentials' };
    }

    const token = generateToken();
    localStorage.setItem('custom-auth-token', token);

    return {};
  }

  async forgetPassword(params: ForgetPasswordParams): Promise<{ error?: string }> {
    try {
      const res = await fetch(`${API_BASE}/customer/forgot_password`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(params),
      });

      const data = await res.json();

      if (!res.ok) {
        return { error: data?.message || 'Something went wrong' };
      }

      return {};
    } catch (err) {
      return { error: err instanceof Error ? err.message : 'Something went wrong' };
    }
  }

  async updatePassword(params: UpdatePasswordParams): Promise<{ error?: string }> {
    try {
      const res = await fetch(`${API_BASE}/customer/update_forget_password`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: params.userId,
          password: params.password,
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        return { error: data?.message || 'Something went wrong' };
      }

      return {};
    } catch (err) {
      return { error: err instanceof Error ? err.message : 'Something went wrong' };
    }
  }

  async getUser(): Promise<{ data?: User | null; error?: string }> {
    // Make API request

    // We do not handle the API, so just check if we have a token in localStorage.
    const token = localStorage.getItem('custom-auth-token');

    if (!token) {
      return { data: null };
    }

    return { data: user };
  }

  async signOut(): Promise<{ error?: string }> {
    localStorage.removeItem("auth_token");
    queryClient.removeQueries({ queryKey: ["auth", "user"] });
    useAuthStore.getState().setLoggingIn(false);
    useAuthStore.getState().setLoggingOut(false);

    return {};
  }
}

export const authClient = new AuthClient();
