'use client';

import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { useLanguage } from './LanguageContext';

interface AuthContextType {
  user: any;
  session: any;
  loading: boolean;
  restaurantId: string | null;
  branchId: string | null;
  userRecord: any;
  signUp: (email: string, password: string, metadata?: any) => Promise<any>;
  signIn: (email: string, password: string) => Promise<any>;
  signOut: () => Promise<void>;
  getCurrentUser: () => Promise<any>;
  isEmailVerified: () => boolean;
  getUserProfile: () => Promise<any>;
  refreshUserRecord: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType>({} as AuthContextType);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within AuthProvider');
  }
  return context;
};

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const [user, setUser] = useState<any>(null);
  const [session, setSession] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [restaurantId, setRestaurantId] = useState<string | null>(null);
  const [branchId, setBranchId] = useState<string | null>(null);
  const [userRecord, setUserRecord] = useState<any>(null);
  const { syncUserLanguage } = useLanguage();

  const loadUser = useCallback(async () => {
    try {
      const res = await fetch('/api/auth/me');
      const data = await res.json();
      if (data.user) {
        setUser({ id: data.user.id, email: data.user.email });
        setSession({ user: data.user });
        setUserRecord(data.user);
        setRestaurantId(data.user.restaurant_id);
        setBranchId(data.user.branch_id);
        if (data.user.preferred_language) {
          syncUserLanguage(data.user.preferred_language);
        }
      } else {
        setUser(null);
        setSession(null);
        setUserRecord(null);
        setRestaurantId(null);
        setBranchId(null);
      }
    } catch {
      setUser(null);
      setSession(null);
    } finally {
      setLoading(false);
    }
  }, [syncUserLanguage]);

  useEffect(() => {
    loadUser();
  }, [loadUser]);

  const signUp = async (email: string, password: string, metadata: any = {}) => {
    const res = await fetch('/api/auth/sign-up', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email,
        password,
        ownerName: metadata.ownerName,
        restaurantName: metadata.restaurantName,
        plan: metadata.plan,
      }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || 'Registration failed');
    setUser({ id: data.user.id, email: data.user.email });
    setSession({ user: data.user });
    setUserRecord(data.user);
    setRestaurantId(data.user.restaurant_id);
    setBranchId(data.user.branch_id);
    if (data.user.preferred_language) syncUserLanguage(data.user.preferred_language);
    return { user: data.user, session: { user: data.user } };
  };

  const signIn = async (email: string, password: string) => {
    const res = await fetch('/api/auth/sign-in', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || 'Invalid email or password');
    setUser({ id: data.user.id, email: data.user.email });
    setSession({ user: data.user });
    setUserRecord(data.user);
    setRestaurantId(data.user.restaurant_id);
    setBranchId(data.user.branch_id);
    if (data.user.preferred_language) syncUserLanguage(data.user.preferred_language);
    return { user: data.user, session: { user: data.user } };
  };

  const signOut = async () => {
    await fetch('/api/auth/sign-out', { method: 'POST' });
    setUser(null);
    setSession(null);
    setUserRecord(null);
    setRestaurantId(null);
    setBranchId(null);
    if (typeof window !== 'undefined') {
      window.location.href = '/login';
    }
  };

  const getCurrentUser = async () => user;
  const isEmailVerified = () => true;
  const getUserProfile = async () => userRecord;
  const refreshUserRecord = async () => { await loadUser(); };

  const value: AuthContextType = {
    user,
    session,
    loading,
    restaurantId,
    branchId,
    userRecord,
    signUp,
    signIn,
    signOut,
    getCurrentUser,
    isEmailVerified,
    getUserProfile,
    refreshUserRecord,
  };

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