import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";

// Define the shape of the consultant profile
interface ConsultantProfile {
  profile_status: 'incomplete' | 'pending' | 'approved' | 'rejected';
  is_pending: boolean;
  is_approved: boolean;
  is_eligible_for_approval: boolean;
  completeness_percentage: number;
  profile_picture: string | null;
  first_name?: string;
  last_name?: string;
  designation?: string;
  phone?: string;
  company_name?: string;
  address?: string;
  number_of_employees?: string;
  nationality?: string;
  state?: string;
  city?: string;
  consultation_fee?: number;
  target_countries?: string[];
  services?: string[];
  specialization?: string[];
  languages?: string[];
  response_time?: string;
  digital_only?: boolean;
  availability?: string;
  comment?: string;
  active_profile?: string;
  profile_completed_date?: string | null;
  approval_requested_date?: string | null;
  approved_date?: string | null;
  rejection_reason?: string | null;
}

// Define the shape of the user data
interface User {
  id: string;
  name: string;
  email: string;
  role: string;
  consultant_profile?: ConsultantProfile | null;
}

// Define the shape of the store
interface UserStore {
  user: User | null;
  isLoggedIn: boolean;
  setUser: (userData: any) => void;
  fetchUser: () => Promise<void>;
  logout: () => void;
  updateConsultantProfile: (profileData: Partial<ConsultantProfile>) => void;
}

// Create the store using Zustand and persist middleware
export const useUserStore = create(
  persist<UserStore>(
    (set, get) => ({
      user: null,
      isLoggedIn: false,

      // ================================================
      // CHANGED: setUser method - Major rewrite
      // ================================================
      // Problem: Registration API returns full response object with nested data
      // Solution: Handle multiple response structures from different APIs
      // ================================================
      setUser: (userData: any) => {
        console.log("🔄 setUser called with:", userData);
        
        let user: User | null = null;
        
        if (!userData) {
          console.error("❌ No user data provided to setUser");
          return;
        }
        
        // ================================================
        // CASE 1: Registration/Login API response structure
        // ================================================
        // API returns: { success: true, message: "...", role: "...", data: {...}, consultant_status: {...} }
        if (userData.data && userData.data.id) {
          console.log("✅ Parsing registration/login API response");
          const apiData = userData.data;
          user = {
            id: String(apiData.id), // Ensure ID is string
            name: apiData.name || '',
            email: apiData.email || '',
            role: apiData.role || 'consultant',
            consultant_profile: apiData.consultant_profile || null
          };
        }
        // ================================================
        // CASE 2: Direct user object (backward compatibility)
        // ================================================
        else if (userData.id && userData.name && userData.email) {
          console.log("✅ Parsing direct user object");
          user = {
            id: String(userData.id),
            name: userData.name,
            email: userData.email,
            role: userData.role || 'consultant',
            consultant_profile: userData.consultant_profile || null
          };
        }
        // ================================================
        // CASE 3: check-auth API response
        // ================================================
        else if (userData.success && userData.data) {
          console.log("✅ Parsing check-auth API response");
          const apiData = userData.data;
          user = {
            id: String(apiData.id || ''),
            name: apiData.name || '',
            email: apiData.email || '',
            role: apiData.role || '',
            consultant_profile: apiData.consultant_profile || null
          };
        } else {
          console.error("❌ Could not parse user data structure:", userData);
          return;
        }
        
        if (user) {
          console.log("✅ Setting user in store:", {
            id: user.id,
            name: user.name,
            role: user.role,
            profile_status: user.consultant_profile?.profile_status
          });
          set({ user, isLoggedIn: true });
        }
      },
      // ================================================
      // END OF CHANGES to setUser
      // ================================================

      // ================================================
      // UNCHANGED: fetchUser method (keep as is)
      // ================================================
      fetchUser: async () => {
        try {
          console.log("🔄 fetchUser() called - getting fresh data from check-auth");
          
          const response = await fetch("/api/frontend/check-auth", {
            method: "POST",
            headers: {
              'Cache-Control': 'no-cache, no-store, must-revalidate',
              'Pragma': 'no-cache'
            }
          });

          if (!response.ok) {
            console.log("❌ Failed to fetch user data");
            return;
          }

          const userData = await response.json();
          
          console.log("📥 check-auth API Response:", {
            success: userData.success,
            role: userData.data?.role,
            hasConsultantProfile: !!userData.data?.consultant_profile,
            profile_status: userData.data?.consultant_profile?.profile_status,
            is_pending: userData.data?.consultant_profile?.is_pending,
            is_approved: userData.data?.consultant_profile?.is_approved
          });
          
          if (userData.success && userData.data) {
            const user: User = {
              id: userData.data.id || '',
              name: userData.data.name || '',
              email: userData.data.email || '',
              role: userData.data.role || '',
              consultant_profile: userData.data.consultant_profile || null
            };
            
            console.log("✅ Store will be set with:", {
              profile_status: user.consultant_profile?.profile_status
            });
            
            set({ user, isLoggedIn: true });
          }
        } catch (error) {
          console.error("❌ Error fetching user data:", error);
        }
      },

      // ================================================
      // UNCHANGED: updateConsultantProfile method (keep as is)
      // ================================================
      updateConsultantProfile: (profileData) => {
        const currentState = get();
        
        if (!currentState.user) {
          console.error("Cannot update consultant profile: No user logged in");
          return;
        }

        console.log("🔄 Updating consultant profile in store:", profileData);
        
        // Create the updated user object
        const updatedUser: User = {
          ...currentState.user,
          consultant_profile: {
            // Start with existing profile or create new one
            ...(currentState.user.consultant_profile || {
              profile_status: 'incomplete',
              is_pending: false,
              is_approved: false,
              is_eligible_for_approval: false,
              completeness_percentage: 0,
              profile_picture: null
            }),
            // Override with new data
            ...profileData
          }
        };

        console.log("✅ Updated user object:", {
          profile_status: updatedUser.consultant_profile?.profile_status,
          is_pending: updatedUser.consultant_profile?.is_pending,
          is_approved: updatedUser.consultant_profile?.is_approved
        });
        
        set({ user: updatedUser });
      },

      // ================================================
      // UNCHANGED: logout method (keep as is)
      // ================================================
      logout: () => {
        set({ user: null, isLoggedIn: false });
        sessionStorage.removeItem("user-store");
      },
    }),
    {
      name: "user-store",
      storage: createJSONStorage(() => sessionStorage),
      // Add version to handle migrations if needed
      version: 1,
      // Optional: You can add migration logic here if needed
      migrate: (persistedState: any, version: number) => {
        if (version === 0) {
          // Handle migration from version 0 to 1
        }
        return persistedState;
      }
    }
  )
);

// Optional: Create a custom hook for consultant-specific operations
export const useConsultantStore = () => {
  const { user, fetchUser, updateConsultantProfile } = useUserStore();
  
  return {
    consultantProfile: user?.consultant_profile,
    refreshProfile: fetchUser, // Just use fetchUser since it gets all data
    updateProfile: updateConsultantProfile,
    isConsultant: user?.role === 'consultant',
    profileStatus: user?.consultant_profile?.profile_status,
    isProfileApproved: user?.consultant_profile?.profile_status === 'approved',
    isProfilePending: user?.consultant_profile?.profile_status === 'pending',
    isProfileIncomplete: user?.consultant_profile?.profile_status === 'incomplete',
    isProfileRejected: user?.consultant_profile?.profile_status === 'rejected'
  };
};